Searching the haystack with grep

Nitin Venkatesh's Gravatar

Nitin Venkatesh
published July 26, 2014, 6 a.m.

Short Version

Syntax: grep [options] pattern [file]

  • -i: ignore case of pattern
  • -v: reverse search
  • -n: display line numbers of lines matching pattern
  • -c: display total count of number of lines matching pattern
  • -e: used to specify multiple patterns

Long Version

grep is used to search for a particular string or pattern within a file or any given input. For example, to find if the word York exists in a file that contains each state of the US,

nitin@jane-saucy:~$ grep York us_states.txt 
New York

Remember that grep is case-sensitive like most *nix commands. So searching for york instead of York will yield no results. To perform a case-insensitive search use the -i command.

nitin@jane-saucy:~$ grep york us_states.txt 
nitin@jane-saucy:~$ grep -i york us_states.txt 
New York

You can also use regular expressions as a search pattern, like so,

nitin@jane-saucy:~$ grep [Zz] us_states.txt 

That gave us a list of states that had the alphabet Z or z in them, which was just one state, Arizona.

You can perform a reverse search, find every line that doesn't match the search pattern using the -v switch.

nitin@jane-saucy:~$ grep -v [Zz] us_states.txt 
## Output truncated for the sake of brevity

To find the line numbers where the pattern was matched, you can use the -n,

nitin@jane-saucy:~$ grep -n New us_states.txt 
30:New Hampshire
31:New Jersey
32:New Mexico
33:New York

To find the total number of lines in a file that match the pattern, use the -c switch,

nitin@jane-saucy:~$ grep -c New us_states.txt 

You can also use multiple search patterns by specifying each pattern with the -e switch

nitin@jane-saucy:~$ grep -e North -e South us_states.txt 
North Carolina
North Dakota
South Carolina
South Dakota

You can also search multiple files with grep, just tack the filenames at the end of the grep command or use the -f switch

nitin@jane-saucy:~$ grep -i new us_states.txt canada_provinces.txt 
us_states.txt:New Hampshire
us_states.txt:New Jersey
us_states.txt:New Mexico
us_states.txt:New York
canada_provinces.txt:New Brunswick

The most common use of grep is to find a needle from a haystack of output from another command by piping like so,

nitin@jane-saucy:~$ history | grep wget
  122  wget -c
  123  wget -c
 1306  history | grep wget

nitin@jane-saucy:~$ ps aux | grep gnome-terminal
nitin     5184  0.0  0.0   4440   624 ?        Ss   22:36   0:00 /bin/sh -c gnome-terminal
nitin     5185  0.3  0.5 660652 22012 ?        Sl   22:36   0:08 gnome-terminal
nitin     5968  0.0  0.0  13648   948 pts/11   S+   23:20   0:00 grep --color=auto gnome-terminal