Java Reference
In-Depth Information
Table 4-2. Grep command-line options
Option Meaning
-c
Count only: don't print lines, just count them
-C
Context; print some lines above and below each line that matches (not implemented in this version;
left as an exercise for the reader)
-f pat-
tern
Take pattern from file named after -f instead of from command line
-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 in Parsing Command-Line Arguments . Here we use it to con-
trol the operation of an application program. As usual, because main() runs in a static con-
text but our application main line does not, we could wind up passing a lot of information in-
to the constructor. To save space, this version just uses global variables to track the settings
from the command line. Unlike the Unix grep tool, this one does not yet handle “combined
options,” so -l -r -i is OK, but -lri will fail, due to a limitation in the GetOpt parser
used.
The program basically just reads lines, matches the pattern in them, and, if a match is found
(or not found, with -v ), prints the line (and optionally some other stuff, too). Having said all
that, the code is shown in Example 4-11 .
Example 4-11. JGrep.java
/** A command-line grep-like program. Accepts some command-line options,
* and takes a pattern and a list of text files.
* N.B. The current implementation of GetOpt does not allow combining short
* arguments, so put spaces e.g., "JGrep -l -r -i pattern file..." is OK, but
* "JGrep -lri pattern file..." will fail. Getopt will hopefully be fixed soon.
Search WWH ::




Custom Search