Previous post:

Next post:

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.

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
Vim 101 Hacks Book

Previous post:

Next post:

{ 2 comments… read them below or add one }

1 Jahman January 15, 2010 at 1:08 pm

Hi,

Another tip ;) , grep is very slow on UTF-8. Use “LANG=C grep …” to increase speed.

$ echo $LANG
en_US.UTF-8
$ time grep ‘^….’ /usr/share/dict/words >/dev/null
real 2m16.795s
user 2m10.536s
sys 0m0.087s

$ export LANG=C
$ time grep ‘^….’ /usr/share/dict/words >/dev/null
real 0m0.031s
user 0m0.028s
sys 0m0.003s

Source: http://rg03.wordpress.com/2009/09/09/gnu-grep-is-slow-on-utf-8/

2 murali February 9, 2010 at 4:32 pm

hi ,
what is d dirrerence between
a. grep “John Doe” my-file > /dev/null 2>&1
b. grep “John Doe” my-file 2>&1 > /dev/null

Leave a Comment

Previous post:

Next post: