Program: Full Grep
Now that we’ve seen how the
regular expressions package works,
it’s time to write Grep2, a full-blown
version of the line-matching program with option parsing. Table 4-3 lists some typical
command-line options that a Unix
implementation of grep might include.
Table 4-3. Grep command-line options
|
Option |
Meaning |
|---|---|
-c |
Count only: don’t print lines, just count them |
-f pattern |
Take pattern from file named after |
-h |
Suppress printing filename ahead of lines |
-i |
Ignore case |
-l |
List filenames only: don’t print lines, just the names they’re found in |
-n |
Print line numbers before matching lines |
-s |
Suppress printing certain error messages |
-v |
Invert: print only lines that do NOT match the pattern |
We discussed the GetOpt class back in Section 2.8. Here we use it to control the operation of an
application program. As usual, since main( ) runs
in a static context but our application main line does not, we could
wind up passing a lot of information into the constructor. Because we
have so many options, and it would be inconvenient to keep expanding
the options list as we add new functionality to the program, we use a
kind of Collection called
a
BitSet to pass all the true/false arguments: true
to print line numbers, false to print filenames, etc. (Collections
are covered in Chapter 7.) A BitSet is much like a
Vector (see Section 7.4) but is specialized to store only boolean values, and is ideal for handling command-line ...
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