Grep usage examples

Last updated:

Search for all occurrences of a string in all files in this directory downwards (recursively)

$ grep -r "criteria" ./

do the same search but ignoring case

$ grep -ri "criteria" ./*

Ignore directories

(in this example, ignore .svn hidden directory)

$ grep -r --exclude-dir=.svn "criteria" ./

Ignore multiple directories

$ grep -r --exclude-dir={.svn,.git,runtime} "criteria" ./

Ignore kinds of files

$ grep -r --exclude=*.log "criteria" ./

Display file names rather than matching lines

(the names of the files whose contents match the search criteria will be output)

$ grep -rl "criteria" ./

Use Perl-compatible Regex

Perl-compatible regular expressions include shortcuts like \w for words, \d for digits and so on.

For more information, see the official website for perl-compatible regular expressions

Search for lines that end in a word and a semicolon ';':

$ grep -rP "\w+;$" ./

Search for a fixed, raw string (no regex)

(Useful for searching PHP or Perl code, for example, because they contain troublesome characters like '$' and '.').

Search for the actual string '$this->some_method().$this->another_method()' in the current directory downwards, recursively:

$ grep -rF '$this->some_method().$this->another_method()' ./

Wrap the string in double quotes if you need to match for a single quote:

$ grep -rF "some ' string ('e'" ./

Return lines that don't match given expression

This is called inverted grep

Example: return all lines that don't include the string "foobar" (upper/lowercase)

$ grep -vi foobar ./

Chain grep calls

You can chain grep calls to create pipelines:

For example: to return lines that don't match "STARTTLS=client|CMD|dhclient" and contain the string "Aug":

Note that the second call to grep has no -r modifier. -r is not used when you are piping other commands to grep

$ grep -rvP "STARTTLS=client|CMD|dhclient" ./ | grep "Aug"

Show surrounding lines in each match

Use -C N where N is the number of surrounding lines you want to show for each match.

$ grep -C 5 "some text" ./*

Pipe arbitrary output to grep (a.k.a. pipe grep)

Similarly to the example above where you pipe the output of a call to grep to another grep call (to further filter the results), you can pipe any output to grep.

For example, to filter the output of man vi for all lines that mention "vim", possibly prefixed by "g" (I've not included all output):

$ man vi | grep -iP "g?vim"

       vim [options] -t tag
       vim [options] -q [errorfile]
       gvim gview evim eview
       rvim rview rgvim rgview

See grep output in less with colours

Grep output is too large and you need to use a pager like less? You can still keep grep output with colours where patterns match!

Use --color=always and add -r to grep call:

$ man vi | grep --color=always -iP "g?vim" | less -r

More info

Dialogue & Discussion