grep command is used to search files for a specific text. This is incredibly powerful command with lots of options.
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.
# grep John /etc/passwd jsmith:x:1082:1082:John Smith:/home/jsmith:/bin/bash 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.
# grep -v John /etc/passwd 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.
# grep -c John /etc/passwd 2
You can also get the total number of lines that did not match the specific pattern by passing option -cv.
# grep -cv John /etc/passwd 39
How to search a text by ignoring the case?
Pass the option -i (ignore case), which will ignore the case while searching.
# grep -i john /etc/passwd jsmith:x:1082:1082:John Smith:/home/jsmith:/bin/bash 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.
# grep -ri john /home/users /home/users/subdir1/letter.txt:John, Thanks for your contribution. /home/users/name_list.txt:John Smith /home/users/name_list.txt:John Doe # grep -ril john /root /home/users/subdir1/letter.txt /home/users/name_list.txt