Minimal Perl for Unix and Linux People | Page 3 | WebReference

Minimal Perl for Unix and Linux People | Page 3


[previous] [next]

Perl as a (Better) Find Command

6.2.1 Augmenting find with Perl

A useful way to exploit their individual strengths is to use find to generate an initial set of pathnames and Perl to eliminate those whose files lack some additional attributes.

For example, any of the following commands could be used as the first stage of a pipeline to take advantage of find's ability to locate files according to their size, name, and timestamp attributes:

Then Perl commands, having forms such as these, could be added as the filtering stage in the pipeline:

In these commands, -A, -B, and -C are placeholders for the file-type attributes of interest, and "!" has the effect of negating the meaning of the following test (as it does with find). Note also that or, being weaker in precedence than and (see section 2.4.5), needs parentheses around its arguments.7

Therefore, Example 2 reports files from its input that have attributes A and B, Example 3 reports those having A but not (!) B, and Example 6 reports those having at least one of A, B, or C.

Here is a pipeline based on Example 1 th at lists regular files under the directory /home/ersimpson that contain text. Although find is used for the regular file (-typef) test, Perl must be used for the text-file test that find doesn't provide:

We'll use this script later in this chapter, in an example that provides a file-validating service for grep.

As an example of a case using or, the following command lists files that are regular (-type f) and either empty or nontext:

The parentheses surrounding or's conditions in that command are critical, due to the higher precedence of and. Without them, a True result from the first test—signifying emptiness—wouldn't lead to the filename being printed as desired, due to implicit parentheses being placed as follows:

Now that we've discussed how to find filenames by file attributes, we'll turn next to finding filenames according the characteristics of the names themselves.


[previous] [next]

URL: