LinuxDevCenter.com
oreilly.comSafari Books Online.Conferences.

advertisement


Unix Power Tools
Build Strings with { }

by Jerry Peek
01/27/2000

I've been finding more and more uses for the {} pattern-expansion characters in csh, tcsh, and bash. 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 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}

Back More Unix Power Tools

 




Linux Online Certification

Linux/Unix System Administration Certificate Series
Linux/Unix System Administration Certificate Series — This course series targets both beginning and intermediate Linux/Unix users who want to acquire advanced system administration skills, and to back those skills up with a Certificate from the University of Illinois Office of Continuing Education.

Enroll today!


Linux Resources
  • Linux Online
  • The Linux FAQ
  • linux.java.net
  • Linux Kernel Archives
  • Kernel Traffic
  • DistroWatch.com


  • Sponsored by: