Minimal Perl for Unix and Linux People: Part 2/Page 3 | WebReference

Minimal Perl for Unix and Linux People: Part 2/Page 3

[previous] [next]

Perl as a (Better) Find Command: Part 2

6.4.2 Recursive grepping

In the previous section, you saw a filename-filtering technique that prevents non- GNU grep commands from searching within binary files, finding accidental matches, and corrupting the screen. But there are occasions when you really want to name a directory as an argument to grep, and have DWIMity16 prevail—which means grep should search within every file in that directory, and the files of its subdirectories. That's called recursive grepping. You'll see how to accomplish this worthy goal next.

Here's the command that formed the initial basis for the text_grep script discussed earlier:

Only a slight change is needed to allow the user to specify a directory instead of a file and to get the appropriate results from any version of grep. You simply replace the ls in that pipeline with a find command that starts in the specified directory and recursively descends into those below it, finding all regular files.

Here's an example that starts its search in /home/ersimpson:

You'll see a scripted version of this recursive grep command in chapter 8, which provides a more grep-like interface:

Despite its many virtues, it's important to recognize that command substitution, as used in the preceding examples, isn't always the most reliable way to pass arguments to commands. For this reason, we'll examine the xargs alternative shortly. But first, we'll wind up this topic with a quick discussion of the widespread applicability of the techniques we've covered thus far.

6.4.3 Perl as a generalized argument pre-processor

Although previous examples focused on the use of Perl commands to preprocess filenames for presentation to the grep command, there's no reason to restrict the use of this type of argument-validation service to any particular utility. On the contrary, you can use it to good advantage with any command that accepts input from text files named as arguments, including sed and awk, and dozens of other Unix utilities.

For instance, here are examples of awk commands benefiting from argument preprocessing provided by Perl:

You'll see additional examples of Perl's usefulness as an argument pre-processor in part 2.

Next, we'll discuss where the much-lauded xargs command can provide advantages over command substitution—and where it can't, but Perl can.

[previous] [next]