Using Command Substitution
Suppose you're working on a program and you decide to change the name of a variable from wdCnt to wordCount everywhere it's used. You can use the following command to identify which C source (.c) and header (.h) files reference the variable:[3]
% grep -l wdCnt *.[ch]But instead of simply displaying the resulting filenames on the terminal, you can tell the shell to run the grep command and pass the names directly to the editor. To do so, simply put the command in backquotes:[4]
% vi `grep -l wdCnt *.[ch]`The shell sees the backquotes and performs a command substitution: it replaces the grep command with its output (after changing newlines to spaces so the output becomes a single line). That way, you can edit the appropriate files without knowing which ones they are beforehand. If the grep command produces the filenames defs.h, fileio.c, main.c, utils.c, and vars.c, the vi command is equivalent to this:
% vi defs.h fileio.c main.c utils.c vars.cCommand substitution is useful in conjunction with other shell facilities such as command history. For example, you might run only the grep command to get an idea of which files contain the variable name, and then use !! to repeat it in the vi command:
%grep -l wdCnt *.[ch]%vi `!!`vi `grep -l wdCnt *.[ch]`
Command substitution is a technique that may, at first, seem esoteric and of limited use. However, it's such a useful method for constructing command lines that it should become an everyday part of your shell-using ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access