Tuesday Tiny Techie Tip

Command substitution

How would you edit all the files in a directory which contained the word "play"?

You could see which files had the pattern by using grep(1):

% grep play *
fire.txt:     You're playing cold music on the bar room floor,
playin.txt:     I'm just playing in the band
playin.txt:     While I'm playing in the band
playin.txt:     For playing in the band
truckin.txt:     once told me you got to play your hand

You can use the -l flag to grep to just list the filenames:
% grep -l play *

But now how do you get the filenames onto the command line of your favorite editor?

Command substitution to the rescue.

Command substitution takes the output of a command and passes it on to the shell for further processing. To use it, place the command whose output you want inside of backticks (`) (Found as the unshifted meaning of the tilde (~) key on most keyboards)

% wc `grep -l play *`
      34     219    1235 fire.txt
      52     186    1151 playin.txt
      69     421    2357 truckin.txt
     155     826    4743 total

(no, wc(1) isn't my favorite text editor, but it produces easier output than sed ;-)

What if I want to look at the contents of a script that's in my path, but I don't know where?

% which sprinfo
% cat `!!`
cat `which sprinfo`

Here's one from the Source Code Control Procedure:

Check in all checked out files in the current view:

% ct ci -c "fixed all the bugs" `ct lsco -cvi -avo -s`

Command substitution is also useful for setting the value of a variable for future reference:
% set foo=`which sprinfo`
% echo $foo
% wc $foo
     138     398    3146 /tools/public/bin/sprinfo
% ls -l $foo
-r-xr-xr-x  1 vobadm       3146 Aug 27 15:06 /tools/public/bin/sprinfo
% $foo
usage: /tools/public/bin/sprinfo <SPR NUMBER>...
   or: /tools/public/bin/sprinfo -l <SPR NUMBER>

We'll look at another place where command substitution is wildly useful next week.

Tuesday Tiny Techie Tip -- 14 January 1997
Forward to (01/21/97)
Back to (01/07/97)
Written by Jeff Youngstrom

Up to the TTTT index

Tuesday Tiny Techie Tips are all © Copyright 1996-1997 by Jeff Youngstrom. Please ask permission before reproducing any of this material.