Build Strings with { }
I've been finding more and more uses for the {}
pattern-expansion characters in csh, tcsh, and bash. (Other shells can use {}
, too; see article .) They're similar to *
, ?
, and []
(), but they don't match filenames the way that *
, ?
, and []
do. You can give them arbitrary text (not just filenames) to expand - that "expand-anything" ability is what makes them so useful.
Here are some examples to get you thinking:
- To fix a typo in a filename (change fixbold5.c to fixbold6.c):
%
mv fixbold{5,6}.c
An easy way to see what the shell does with
{}
is by adding echo () before the mv:%
echo mv fixbold{5,6}.c
mv fixbold5.c fixbold6.c
- To copy filename to filename.bak in one easy step:
%
cp filename{,.bak}
- To print files from other directory(s) without retyping the whole pathname:
%
lpr /usr3/hannah/training/{ed,vi,mail}/lab.{ms,out}
That would give lpr () all of these files:
/usr3/hannah/training/ed/lab.ms /usr3/hannah/training/ed/lab.out /usr3/hannah/training/vi/lab.ms /usr3/hannah/training/vi/lab.out /usr3/hannah/training/mail/lab.ms /usr3/hannah/training/mail/lab.out
in one fell swoop!
- To edit ten new files that don't exist yet:
%
vi /usr/foo/file{a,b,c,d,e,f,g,h,i,j}
That would make /usr/foo/filea, /usr/foo/fileb, ... /usr/foo/filej. Because the files don't exist before the command starts, the wildcard
vi
/usr/foo/file[a-j]
would not work (). - An easy way to step through three-digit numbers 000, 001, ..., 009, 010, 011, ..., 099, 100, 101, ... 299 is:
foreach
foreach n ({0,1,2}{0,1,2,3,4,5,6,7,8,9}{0,1,2,3,4,5,6,7,8,9}) ...Do whatever with the number $n... end
Yes, csh also has built-in arithmetic, but its
@
operator () can't make numbers with leading zeros. This nice trick shows that the{}
operators are good for more than just filenames. - To create sets of subdirectories:
%
mkdir man
%mkdir man/{man,cat}{1,2,3,4,5,6,7,8}
%ls -F man
cat1/ cat3/ cat5/ cat7/ man1/ man3/ man5/ man7/ cat2/ cat4/ cat6/ cat8/ man2/ man4/ man6/ man8/
- To print ten copies of the file project_report (if your lpr () command doesn't have a -#10 option):
%
lpr project_repor{t,t,t,t,t,t,t,t,t,t}
- JP