Java Reference
In-Depth Information
Printing Lines Containing a Pattern
Problem
You need to look for lines matching a given regex in one or more files.
Solution
Write a simple grep -like program.
Discussion
As I've mentioned, once you have a regex package, you can write a grep -like program. I
gave an example of the Unix grep program earlier. grep is called with some optional argu-
ments, followed by one required regular expression pattern, followed by an arbitrary number
of filenames. It prints any line that contains the pattern, differing from Printing All Occur-
rences of a Pattern , which prints only the matching text itself. For example:
grep "[dD]arwin" *.txt
The preceding code searches for lines containing either darwin or Darwin in every line of
every file whose name ends in .txt . [ 19 ] Example 4-6 is the source for the first version of a pro-
gram to do this, called Grep0 . It reads lines from the standard input and doesn't take any op-
tional arguments, but it handles the full set of regular expressions that the Pattern class im-
plements (it is, therefore, not identical to the Unix programs of the same name). We haven't
covered the java.io package for input and output yet (see Chapter 10 ), but our use of it here
is simple enough that you can probably intuit it. The online source includes Grep1 , which
does the same thing but is better structured (and therefore longer). Later in this chapter, Pro-
gram: Full Grep presents a JGrep program that uses my GetOpt (see Parsing Command-Line
Arguments ) to parse command-line options.
Example 4-6. Grep0.java
public
public class
class Grep0
Grep0 {
public
public static
static void
void main ( String [] args ) throws
throws IOException {
BufferedReader is =
new
new BufferedReader ( new
new InputStreamReader ( System . in ));
iif ( args . length != 1 ) {
System . err . println ( "Usage: MatchLines pattern" );
 
Search WWH ::




Custom Search