Hack 17. Grep Command Examples

by Ramesh

grep command is used to search files for a specific text. This is incredibly powerful command with lots of options.

  1. Syntax: grep [options] pattern [files]

How can I find all lines matching a specific keyword on a file?

In this example, grep looks for the text John inside /etc/passwd file and displays all the matching lines.

  1. # grep John /etc/passwd
  2.  
  3. jsmith:x:1082:1082:John Smith:/home/jsmith:/bin/bash
  4. jdoe:x:1083:1083:John Doe:/home/jdoe:/bin/bash

Option -v, will display all the lines except the match. In the example below, it displays all the records from /etc/password that doesn’t match John.

Note: There are several lines in the /etc/password that doesn’t contain the word John. Only the first line of the output is shown below.

  1. # grep -v John /etc/passwd
  2.  
  3. jbourne:x:1084:1084:Jason Bourne:/home/jbourne:/bin/bash

How many lines matched the text pattern in a particular file?

In the example below, it displays the total number of lines that contains the text John in /etc/passwd file.

  1. # grep -c John /etc/passwd
  2. 2

You can also get the total number of lines that did not match the specific pattern by passing option -cv.

  1. # grep -cv John /etc/passwd
  2. 39

How to search a text by ignoring the case?

Pass the option -i (ignore case), which will ignore the case while searching.

  1. # grep -i john /etc/passwd
  2.  
  3. jsmith:x:1082:1082:John Smith:/home/jsmith:/bin/bash
  4. jdoe:x:1083:1083:John Doe:/home/jdoe:/bin/bash

How do I search all subdirectories for a text matching a specific pattern?

Use option -r (recursive) for this purpose. In the example below, it will search for the text “John” by ignoring the case inside all the subdirectories under /home/users.

This will display the output in the format of “filename: line that matching the pattern”. You can also pass the option -l, which will display only the name of the file that matches the pattern.

  1. # grep -ri john /home/users
  2.  
  3. /home/users/subdir1/letter.txt:John, Thanks for your contribution.
  4. /home/users/name_list.txt:John Smith
  5. /home/users/name_list.txt:John Doe
  6.  
  7. # grep -ril john /root
  8.  
  9. /home/users/subdir1/letter.txt
  10. /home/users/name_list.txt