How To Use grep Command In Linux / UNIX

by Vivek Gite · 66 comments

How do I use grep command in Linux?

grep command searches the given file for lines containing a match to the given strings or words. By default, grep prints the matching lines. Use grep to search for lines of text that match one or many regular expressions, and outputs only the matching lines.

The name, "grep", derives from the command used to perform a similar operation, using the Unix/Linux text editor ed:
g/re/p

grep command syntax

grep 'word' filename
grep 'string1 string2'  filename
cat otherfile | grep 'something'
command | grep 'something'

Use grep to search file

Search /etc/passwd for boo user:
$ grep boo /etc/passwd

You can force grep to ignore word case i.e match boo, Boo, BOO and all other combination with -i option:
$ grep -i "boo" /etc/passwd

Use grep recursively

You can search recursively i.e. read all files under each directory for a string "192.168.1.5"
$ grep -r "192.168.1.5" /etc/

Use grep to search words only

When you search for boo, grep will match fooboo, boo123, etc. You can force grep to select only those lines containing matches that form whole words i.e. match only boo word:
$ grep -w "boo" /path/to/file

Use grep to search 2 different words

use egrep as follows:
$ egrep -w 'word1|word2' /path/to/file

Count line when words has been matched

grep can report the number of times that the pattern has been matched for each file using -c (count) option:
$ grep -c 'word' /path/to/file
Also note that you can use -n option, which causes grep to precede each line of output with the number of the line in the text file from which it was obtained:
$ grep -n 'word' /path/to/file

Grep invert match

You can use -v option to print inverts the match; that is, it matches only those lines that do not contain the given word. For example print all line that do not contain the word bar:
$ grep -v bar /path/to/file

UNIX / Linux pipes and grep command

grep command often used with pipes. For example print name of hard disk devices:
# dmesg | egrep '(s|h)d[a-z]'
Display cpu model name:
# cat /proc/cpuinfo | grep -i 'Model'
However, above command can be also used as follows without shell pipe:
# grep -i 'Model' /proc/cpuinfo

How do I list just the names of matching files?

Use the -l option to list file name whose contents mention main():
$ grep -l 'main' *.c
Finally, you can force grep to display output in colors:
$ grep --color vivek /etc/passwd
If you enjoyed the grep tutorial, then you might like to read our "Regular Expressions in Grep" tutorial.

Featured Articles:

Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our daily email newsletter to make sure you don't miss a single tip/tricks. Subscribe to our weekly newsletter here!

{ 66 comments… read them below or add one }

1 Ivan 06.16.08 at 11:22 pm

I found this tutorial being the most clear and helpful one. Thank you.

2 manik sikka 11.25.08 at 12:26 am

This Tutorial is so far helpful to me.

Thank you..!!

3 turbolinux 12.12.08 at 11:46 am

what if i want to search keyword
like “$this->Products” or “['status']” ?

grep -R "['status']" 

doesnt work

4 Vivek Gite 12.12.08 at 11:53 am

Try

grep -R "\['status'\]"  filename
5 Arunkumar 12.26.08 at 5:32 am

this is very useful to me.. thanks …

6 Vikram 01.30.09 at 11:39 am

Very helpful. saved my time.

7 Domino 03.18.09 at 9:40 pm

What is the best way to grep recursively through a directory tree, and display the pattern matches, that occur in just all the *.cpp files?

For example:

grep -HRn “look for this” *.cpp

doesn’t work (on Linux)

8 eswar 03.23.09 at 9:02 am

what if i want to search like this

9 Tauqueer 03.25.09 at 8:13 am

Hi
I want to search t1.spq, t2.spq ….. tn.spq words from a file
grep -i “*.spq” filename doesn’t work
Please tell how can search such words??

-Regards,
tauqueer

10 eswar 03.25.09 at 9:45 am

avoid using * grep -i “spq” tt.sh
then you will get all the words which will have spq.
if some thing need to refrained from that need to get the desired out put then use

grep -i “spq” tt.sh | grep -v ” somepattern”

11 Humphrey 04.25.09 at 9:03 am

How can i grep for an output that come after a statement: eg Expires: 10/May/2009.

If i want to caputure only the date, how can i grep for what comes after the colon (:)

please help

12 Vivek Gite 04.25.09 at 10:21 am

Try,

echo 'Expires: 10/May/2009' | cut -d: -f2
OR
echo 'Expires: 10/May/2009' | awk -F':' '{ print $2}'

13 Rizvana 04.29.09 at 6:01 pm

This is quite informative…… Thanks.

Also I have a question, what is the expansion of ‘grep’? Can anyone answer?

14 Ravi 04.30.09 at 7:30 am

This helps a lot,,

15 Humphrey 05.02.09 at 12:11 am

Rizvana,
grep means Get Regular Expression and Print

16 Humphrey 05.02.09 at 8:44 pm

How can i do calculation on dates;
eg to know the number of days between ‘todays date’ and a day like ‘15/may/2009′

please help

17 divya 05.04.09 at 2:24 pm

thanks .i gt the rite information.

18 Blury 05.11.09 at 3:34 am

Hi,
How can I use grep function to search files that file name with “ord” or “rec” from specific dir??

19 kandida 06.02.09 at 7:04 am

Hi
lets say i have some data :
a
a
a
b
b
b
c
c
c
can I use grep comand to make like this :
a
b
c
thanks

20 Vivek Gite 06.02.09 at 8:04 am

Try uniq command.

21 kandida 06.02.09 at 9:52 am

Vivek,
its working…..thanks a lot

22 Blury 06.03.09 at 12:51 am

Hi,
No one know how to use grep function to search files that file name with “ord” or “rec” from specific dir??

23 Vivek Gite 06.03.09 at 1:03 am

Try

cd /dir/to/search
grep "word" ord*
grep -R "word" rec*
24 snake 06.10.09 at 3:46 pm

Hi,
I’d like to get the total cpu and memory usage easily and I think of using ‘dstat’ command. Can I get the values corresponding to the free and used column with grep?

------memory-usage-----
used buff cach free
153M 876k 24M 4392k

cheers!

25 Nazeem S 06.22.09 at 10:34 am

The Most Helpful POST

26 Thomas K 06.26.09 at 1:36 pm

For those who want to search files with wild cards and the like, try the find command with -exec. find /dir/to/search/ -iname *.cpp -exec grep 'word' '{}' \;
and snake, I do not think it is possible to search columns with grep, I’m 98% sure that it is line (row) only.

27 sankar 07.10.09 at 6:45 am

As i was i beginner , it helped me a lot . I would like to thank all the people who contributed it to the public … than you so much

28 manavi 07.25.09 at 4:01 am

whats the use of egrep and fgrep
give examples of both

29 Vivek Gite 07.25.09 at 6:22 am

egrep is for regex and fgrep is for fixed string. I will update FAQ with more examples.

30 SANA 08.02.09 at 4:35 am

this is the best and the most understandable tutorial i have seen till date.
GOOD WORK!!

31 Patrick 08.07.09 at 10:43 am

This tutorial is very easy to follow and enabled me to learn so much within a very short time

32 prathamesh 08.07.09 at 10:52 am

hi this is really really helpful and very fast introduction for grep very nice

33 harshal 08.08.09 at 10:27 am

exact and accurate content with no irrelevent text..

34 Rob 08.11.09 at 7:19 am

clean and accurate .thanks

35 Syed 08.16.09 at 1:40 pm

Can someone help me for a data like:

aa:abc
bb:def
cc:ghi
dd:ijk

aa:lmn
bb:opq
cc:
dd:uvw

aa:pqr
bb:stu
cc:vwx
dd:yza

Description of data:
aa, bb, cc, dd comprise one record. Blank line is dividing 100 of such records.
question1) How to grep “cc:” that is empty value? i am unable to do this because it gives all the values.
question2) I need to print value of “aa:…” for all the records whose “dd:uvw”. How to do this?

36 jyothi 09.17.09 at 12:35 pm

hi all..
can anyone please explain me about this command
ps -ef|grep -v grep|grep $orasid >>/dev/null

37 learner 09.22.09 at 11:39 pm

ok..i feel really dumb..but i got this task i have to do to find a hidden file or something like that and im pretty sure i would use the command ls or whatever.
my problem is i dont no what im doing at all here..were do i type the command in at? all these things jus teach u the commands. yea im dumb i dont have a clue were to type it in..
if someone could please help me out here it be much appreciated! thanx

38 jyothi 09.23.09 at 12:56 pm

hii..
It goes something like this..
i want to list a oracle database instance (say orasid=tiger) using this command..
I issued each command in separate and could understand little bit..
1. ps -ef :: lists all running processes
2. the output is directed to “grep -v grep” now
3. what that command does is just filter out any text containing ‘grep’..
4. this output is now sent to “grep $orasid”
5. it will just fetch only those running process like ” tiger ”
6. the output is redirected to /dev/null where the output is just discarded..
after this command here they used
if[ $? -ne 0]
then ————–
else —————–
fi
where $? reads output of previous command…
here $? is 0 as the command hasn’t thrown any error

39 AKHIL 09.23.09 at 5:03 pm

VERY HELPFUL

40 Samer 09.27.09 at 6:49 am

Dear All ,
Thnaks for this nice chart it helps me a lot .
1- If i need to search for a “word” inside a directory that holds files, these files are located in the “www”
2- Also to search for a “word” in the all the databases in : /var/lib/mysql/database

Thanx all

41 ed 09.27.09 at 11:48 pm

What is the grep command to find a string of charactes like below

KY 41099-1000

I am just using KY as an example but I want the command to list any state abbreviations followed by a 9 digit zip code. Any help is appreciated

42 nitin 09.30.09 at 5:06 pm

@ed
use
# grep ^[A-Z][A-Z] [0-9] [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$ filename

i hope it work………

43 faiz_zaidy 10.03.09 at 11:52 am

please solve my query
my query is “how can i search the text in hole file of a particular dirctory”

44 Sam 10.18.09 at 7:46 pm

Hi i wud like an explanation of the ff command
grep[a-g]…[r-z]text.txt

45 Mukesh 10.25.09 at 1:44 am

This Tutorial is very helpful to me.

Thanks….!!

46 dev 11.11.09 at 4:26 am

@ Syed:

** answer1 **
cat file | grep '^cc:$'
will produce only cc: with no value.
Learn regular expressions. In the command above regular expression is between ”. So… cat is normal command that prints file. Then result is piped (|) to grep, which processes it with regular expression (^cc:$).
This regex basically matches lines, which contain:
^ – beginning of the line
c – letter c
c – letter c
: – colon
$ – end of line
If there is something between colon (:) and end of line ($), in your case some value, then line is not produced by grep.

** answer2 **
How to check value of aa: in the record which contain dd:uvw?
cat file | grep -B3 'dd:uvw'
-B3 tells grep to show line that matches our pattern and 3 lines Before (you can change this number if you want, you can use -A4 to show 4 lines After).
So the command above will produce whole 4 line of each record, which contain dd:uvw. To show only lines with aa: and their values, we can simply add subsequent grep:
cat file | grep -B3 'dd:uvw' | grep 'aa'
…and that’s it.

47 dev 11.11.09 at 4:37 am

@Sam
grep [a-g]…[r-z]text.txt
will match files which names start with a,b,c,d,e,f or g, then there are subsequent three characters – each dot (.) represent any character – then there is r,s,t,u,v,w,x,y or z and then text.txt.
So it can be:
bokkrtext.txt
aiiiztext.txt
and so on…

48 dev 11.11.09 at 5:14 am

@ jyothi
ps -ef|grep -v grep|grep $orasid » /dev/null

Explanation:
ps -ef lists processes. On that list there is number of every process, even number of grep process executed in this line. For example if i try to grep non-existing process john by issuing command ps -ef | grep john, then i will get this:
dev 6271 5933 0 05:43 pts/0 00:00:00 grep john
Even if there is no process I am looking for, I will get result from grep. I don’t want that to happen, so I will have to grep invert match (grep -v pattern as explained in the howto above).
In other words ps -ef | grep -v grep will list processes excluding grep.

After next pipe you have:
grep $orasid
$string recalls value of variable defined before.
If you define $orasid=bob, then your command will be equal to:
ps -ef | grep -v grep | grep bob » /dev/null
If $orasid=william, then your command will be equal to:
ps -ef | grep -v grep | grep william » /dev/null
and so on…

» /dev/null redirects output of the command to nowhere, because we don’t want to see grep output on our screen, when executing the code.

Summarizing:

$orasid=tiger
...
ps -ef | grep -v grep | grep $orasid >> /dev/null
...
if [ $? -ne 0]
then echo 'claws'
else echo 'no claws'
fi

If there is process named tiger (output of grep is not empty), then we get claws, else we get no claws :)

49 marlenchen 11.16.09 at 7:45 pm

How can i search users, who can sign in in the system, with the grep commando?

50 swarna 12.01.09 at 8:12 pm

very useful to me..

51 parveen dabas 12.03.09 at 6:38 am

i found this tutorial really helpful…
well i hv one doubt…
if i have two files, namely..
cat >file1
1
2
3
4
cat >file2
1
2
Now wat command and iptions to use if i want only 3 and 4 as output i.e.
only those lines which are not present in file2 wen compaed to file1… plz help….

52 krishna 12.03.09 at 1:17 pm

Simply super ,,,thanks

53 Shan 12.14.09 at 5:07 pm

This is great article , i am using the windows Grep editor, I am search the text content \”*hello*\” to get the world hello in all the files. I didnt get any output . Could suggest me what i should use.

54 parveen dabas 12.15.09 at 9:44 am

Reply to Shan
wel u can use
grep -iw hello filename
if two words ex. Hello and
Hi, use foll syntax
egrep -iw ‘hello|Hi filename

55 Ram 01.12.10 at 9:57 pm

Please do explain, what do the values between colons represent? For example:

grep video /etc/groups

video:x:33:rtalkad

56 Vivek Gite 01.13.10 at 4:25 am

See /etc/group file format.

57 hammy 01.25.10 at 10:21 am

How to count total number of lines using shell script..????

58 Runal 01.28.10 at 10:44 am

Hi
I have an outstanding issue with me…
i know the specific pattern in the file but dont know the name of the file/script and dont know the location either.
How to search the filename with simply the pattern in that file.

Actually at some xyz location a .dmp file gets created (xyz.dmp (everyday it creates the same file as it a daily backup.))…now i dont know which script creates this .dmp file…So i need to know the name of the script.

59 Marco 01.30.10 at 3:33 am

Well, I didn’t found an answer, maybe you can help me.

I look for something like:

grep “[string a] AND [string b]” (print all lines who include [string a] and [string b])
grep “[string a] OR [string b]” (print all lines who include [string a] or [string b])
grep “NOT [string a]” (print all lines except [string a])

60 Salman 01.30.10 at 10:59 pm

@Hammy

In order to count “words” , “characters” and “lines” in a file there is a bash command called “wc”.

example:

wc -l < filename
or
cat filename | wc -l
will count number of lines in file named "filename"

wc -w < somefile
cat somefile | wc -w
will count number of words or strings in the file named "somefile"

wc -c < somefile
cat somefile | wc -c
will count number of characters in the file named "somefile"

cheers!!

61 esakki 02.11.10 at 5:50 am

How can i found system ip with mac address using grep command, pls tell anyone.

62 my11 02.22.10 at 8:19 pm

how do u run a grep cmd to exclude multiple lines from a file and write remaining lines to a file?

63 naveen.divi 02.25.10 at 7:58 am

this is tutorial is very helpful for me.

thanks a lot.

64 linu 02.25.10 at 9:20 am

REALLY GREAT BLOG!!1

65 novice 03.03.10 at 6:29 am

hi, I am trying to to something like this…

filename_$CLIENT_NUMBER_sapphire_$DATE.var
filename_0_sapphire_20102002.var
filename_1_sapphire_20102002.var

filename_22_sapphire_20102002.var
filename_23_sapphire_20102002.var

so i wanna get a list of all these vars that are set for a certain day for all the client_number(0 to 24)… in an ordered fashion.

set | grep 20102002 | grep filename_ — gives me the 0 file and then 10, 11… and then the 1, 2 (filename_0_sapphire_20102002.var)

i have tried sort and got no results. Please can u help.

did this too:
set | grep 20102002 | grep filename_ ‘[0-9]‘ — and get only 0 to 9 vars… how do i get 0 to 23 in order.

Thanks!

66 dillip kumar jena 03.12.10 at 10:53 am

really it is very help ful to me.

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Previous FAQ:

Next FAQ:

nixCraft FAQ PDF Collection Now Available To All