OnWorks Linux and Windows Online WorkStations

Logo

Free Hosting Online for WorkStations

< Previous | Contents | Next >

Brace Expansion

Perhaps the strangest expansion is called brace expansion. With it, you can create multi- ple text strings from a pattern containing braces. Here's an example:



[me@linuxbox ~]$ echo Front-{A,B,C}-Back

Front-A-Back Front-B-Back Front-C-Back

[me@linuxbox ~]$ echo Front-{A,B,C}-Back

Front-A-Back Front-B-Back Front-C-Back


Patterns to be brace expanded may contain a leading portion called a preamble and a trailing portion called a postscript. The brace expression itself may contain either a comma-separated list of strings, or a range of integers or single characters. The pattern may not contain embedded whitespace. Here is an example using a range of integers:



[me@linuxbox ~]$ echo Number_{1..5}

Number_1 Number_2 Number_3 Number_4 Number_5

[me@linuxbox ~]$ echo Number_{1..5}

Number_1 Number_2 Number_3 Number_4 Number_5


Integers may also be zero-padded like so:



[me@linuxbox ~]$ echo {01..15}

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15

[me@linuxbox ~]$ echo {01..15}

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15


[me@linuxbox ~]$ echo {001..15}

001 002 003 004 005 006 007 008 009 010 011 012 013 014 015

[me@linuxbox ~]$ echo {001..15}

001 002 003 004 005 006 007 008 009 010 011 012 013 014 015

A range of letters in reverse order:



[me@linuxbox ~]$ echo {Z..A}

Z Y X W V U T S R Q P O N M L K J I H G F E D C B A

[me@linuxbox ~]$ echo {Z..A}

Z Y X W V U T S R Q P O N M L K J I H G F E D C B A


Brace expansions may be nested:



[me@linuxbox ~]$ echo a{A{1,2},B{3,4}}b

aA1b aA2b aB3b aB4b

[me@linuxbox ~]$ echo a{A{1,2},B{3,4}}b

aA1b aA2b aB3b aB4b


So what is this good for? The most common application is to make lists of files or direc- tories to be created. For example, if we were photographers and had a large collection of images that we wanted to organize into years and months, the first thing we might do is create a series of directories named in numeric “Year-Month” format. This way, the direc- tory names will sort in chronological order. We could type out a complete list of directo- ries, but that's a lot of work and it's error-prone too. Instead, we could do this:


image

[me@linuxbox ~]$ mkdir Photos

[me@linuxbox ~]$ cd Photos

[me@linuxbox Photos]$ mkdir {2007..2009}-{01..12}

[me@linuxbox Photos]$ ls


2007-01

2007-07

2008-01

2008-07

2009-01

2009-07

2007-02

2007-08

2008-02

2008-08

2009-02

2009-08

2007-03

2007-09

2008-03

2008-09

2009-03

2009-09

2007-04

2007-10

2008-04

2008-10

2009-04

2009-10

2007-05

2007-11

2008-05

2008-11

2009-05

2009-11

2007-06

2007-12

2008-06

2008-12

2009-06

2009-12


Pretty slick!


Top OS Cloud Computing at OnWorks: