WSU logo


College of Engineering & CS
Wright State University
Dayton, Ohio 45435-0001

CEG 333: Introduction to Unix

Prabhaker Mateti

grep


Grep is a tool for searching for text in files. Given a regular expression, grep displays every matching line in a file (or standard input).

Option Meaning
grep PATTERN [FILENAME...] Print all the lines matching a SMRE PATTERN in the given files. If no files are given, search stdin.
-i Make the search case-insensitive ("a" will match both "a", and "A").
-r Recurse through the given directories.
-v Invert the search: match every line not containing PATTERN.
-A NUM Show NUM lines of context after every matching line.
-B NUM Show NUM lines of context before every matching line.
-C NUM Show NUM lines of context before and after every matching line.
-c Print only a count of matching lines, not the matches themselves.
-E Use extended regular expressions (allows for more complex patterns). Equivalent to the egrep command.

Example 1: find all lines in either files under the "CEG333" directory or the ./README file which contain "Unix" or "Linux", with any capitalization.

"(uni|linu)x" is a regular expression meaning "either uni or linu followed by an x", so:

      $ grep -ri (uni|linu)x CEG333 README
      -bash: syntax error near unexpected token `('
    

Oops. Many of the special characters in regular expressions also have special meaning to the shell. When the shell sees them, it tries to interpret them and fails. So most regular expressions should be quoted (enclosed in quotation marks) so that the shell knows to just pass them along to grep.

Note: double (") and single (') quotation marks have slightly different meanings (see "man bash"). Usually, single quotes should be used.

      $ grep -ri '(uni|linu)x' CEG333 README
    

This time, grep prints some lines, but they aren't the ones the pattern should match. Notice the -E option in the above table? By default, grep assumes that the pattern is a basic regular expression, in which fewer characters have a special meaning. To correctly execute the regular expression, either put grep into extended mode:

      $ grep -Eri '(uni|linu)x' CEG333 README
    

or escape the special syntax (with backslashes) to tell grep it should retain its meaning:

      $ grep -ri '\(uni\|linu\)x' CEG333 README
    

Example 2: show a ps listing without kernel processes (those that have their names enclosed in square brackets).

      $ ps aux | grep -v '\[.*\]'
    

Since it's likely large, it may be better to view it one screen-full at a time ("less" is a pager. Another, simpler, pager is "more"):

      $ ps aux | grep -v '\[.*\]' | less