Hack #7-> Grep Command
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
In this example, grep looks for the text John inside /etc/passwd file and
displays all the matching lines.
# grep John /etc/passwd
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
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
How many lines matched the text pattern in a particular
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
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
How to search a text by ignoring the case?
Pass the option -i (ignore case), which will ignore the case while
# grep -i john /etc/passwd
How do I search all subdirectories for a text matching a
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
# grep -ril john /root