grep ­ Global Regular Expression Match and Print

The general syntax for grep is:

grep options pattern filename

For example, grep -n hedgehog verse, would search through the file verse, display all the lines containing the pattern hedgehog and with the extra option, -n, display the line numbers.

Some Options

-c
display a count of the number of lines containing the pattern.
-i
ignore case of search strings
-n
display line numbers
-v
display all the lines not containing the pattern.

Example

To print out the lines not containing the string fond of hedgehogs, in the files poem2, poem3 and poem4 type

grep -v 'fond of hedgehogs' poem[2-4]

Note, because the pattern contains spaces, delimiting quotes are required.

Example using grep in a pipeline
To find out if mary is logged in, without printing the entire list of logged-in users, type

who | grep mary

Example finding patterns in specific positions
How can we list only the sub-directories in the present working directory? The command ls -l will output a long listing for each file entry. The lines beginning with d are directories. The output of ls -l can therefore be piped into grep with the pattern '^d'. The pattern has been modified with a special character ^, meaning at the start of each line. This pattern is referred to as a regular expression.

ls -l | grep '^d'

Only the lines which begin with d (ie directory entries) will be listed.

Help: for more information see grep(1).