< Zurück | Inhalt | Weiter >

1.3.8 The grep Command

No discussion of Linux commands would be complete without mentioning grep. Grep, an acronym for “generalized regular expression processor,” is a tool for searching through the contents of a file. It searches not just for fixed sequences of characters, but can also handle regular expressions.

In its simplest form, grep myClass *.java will search for and display all lines from the specified files that contain the string myClass. (Recall that the *.java expansion is done by the shell, listing all the files that end with


The first parameter to grep, myClass in the example above, is the string that you want to search for. But the first nonoption parameter to grep is con- sidered a regular expression meaning that it can contain special characters for pattern matching to make for more powerful searches (see Section 2.2.3). Some of the most common option parameters for grep are listed in Table 1.2.

Here’s a quick example:

grep println *.java | grep -v System.out

It will look for every occurrence of println but then exclude those that contain

System.out. Be aware that while it will exclude lines like


it will also exclude lines like this:

file.println(msg); // I'm not using System.out

It is, after all, just doing string searches.

Table 1.2 Options for grep









Ignore upper/lower case differences in its matching. Only list the filename, not the actual line that matched. Show the line number where the match was found.

Reverses the meaning of the search—shows every line that does not match the pattern.