Here's an example. Assume you want to edit all files in the current directory that contain the word "error." Type this:
But why does this work? How did we build the incantation above? First, think about how you'd do this without using any special techniques. You'd use grep to find out which commands contain the word "error"; then you'd use vi to edit this list:
Is there any way to compress these into one command? Yes, by using command substitution. First, we need to modify our grep command so that it only produces a list of filenames, rather than filenames and text. That's easy; use grep -l :
The -l option lists each filename only once, even if many lines in the file match. (This makes me think that grep -l was designed with precisely this application in mind.) Now, we want to edit these files; so we put the grep command inside backquotes, and use it as the argument to vi :
You might be wondering about the difference between the "vertical" output from grep , and the "horizontal" way that people usually type arguments on a command line. The shell handles this with no problems. Inside backquotes, both a newline and a space are argument separators.
The list you use with command substitution doesn't have to be filenames. Let's see how to send ato all the users logged on to the system now. You want a command line like this:
Getting there takes a little thinking about what UNIX commands you need to run to get the output you want. (This is real "Power Tools" stuff!) To get a list of those users, you could use . The who output also lists login time and other information - but you can cut that off with a command like :
Some users are logged on more than once. To get a unique list, use. You're done. Just put the name-making command line between backquotes:
If you aren't sure how this works, replace the command you want to run with:
After using UNIX for awhile, you'll find that this is one of its most
useful features. You'll find many situations where you
use one command to generate a list of words, then put that command in
backquotes and use it as an argument to something else.
Sometimes you'll want to
This book has many, many examples of command substitution. Here are some of them:, , , , , , , and .