September 25, 2009
Grep is the quintessential unix utility: it has a funny name, has more command-line switches than a Swiss Army knife has blades, and dates to prehistoric times. In its simplest incarnation,
grep takes a regular expression and a file and prints those lines of the file that match the regular expression.
Since we wrote a regular-expression matcher in the three previous exercises, it is easy to write our own version of
grep. We’ll keep it simple:
grep [-v] regex [file ...]
-v flag inverts the sense of the match: print only those lines that do not match the regular expression. One or more files may be named on the command line; if so, the filename is printed before each matching (or non-matching, for
-v) line. If no filename is given,
grep reads from standard input. All output goes to standard output.