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
Featured Articles:
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- My 10 UNIX Command Line Mistakes
- 10 Greatest Open Source Software Of 2009
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- Top 20 OpenSSH Server Best Security Practices
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Linux Video Editor Software
- Email FAQ to a friend
- Download PDF version
- Printable version
- Comment RSS feed
- Last Updated: 06/3/09




{ 60 comments… read them below or add one }
I found this tutorial being the most clear and helpful one. Thank you.
This Tutorial is so far helpful to me.
Thank you..!!
what if i want to search keyword
like “$this->Products” or “['status']” ?
doesnt work
Try
this is very useful to me.. thanks …
Very helpful. saved my time.
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)
what if i want to search like this
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
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”
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
Try,
echo 'Expires: 10/May/2009' | cut -d: -f2OR
echo 'Expires: 10/May/2009' | awk -F':' '{ print $2}'This is quite informative…… Thanks.
Also I have a question, what is the expansion of ‘grep’? Can anyone answer?
This helps a lot,,
Rizvana,
grep means Get Regular Expression and Print
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
thanks .i gt the rite information.
Hi,
How can I use grep function to search files that file name with “ord” or “rec” from specific dir??
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
Try uniq command.
Vivek,
its working…..thanks a lot
Hi,
No one know how to use grep function to search files that file name with “ord” or “rec” from specific dir??
Try
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!
The Most Helpful POST
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.
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
whats the use of egrep and fgrep
give examples of both
egrep is for regex and fgrep is for fixed string. I will update FAQ with more examples.
this is the best and the most understandable tutorial i have seen till date.
GOOD WORK!!
This tutorial is very easy to follow and enabled me to learn so much within a very short time
hi this is really really helpful and very fast introduction for grep very nice
exact and accurate content with no irrelevent text..
clean and accurate .thanks
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?
hi all..
can anyone please explain me about this command
ps -ef|grep -v grep|grep $orasid >>/dev/null
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
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
VERY HELPFUL
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
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
@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………
please solve my query
my query is “how can i search the text in hole file of a particular dirctory”
Hi i wud like an explanation of the ff command
grep[a-g]…[r-z]text.txt
This Tutorial is very helpful to me.
Thanks….!!
@ 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.
@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…
@ 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 johnEven 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 :)
How can i search users, who can sign in in the system, with the grep commando?
very useful to me..
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….
Simply super ,,,thanks
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.
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
Please do explain, what do the values between colons represent? For example:
grep video /etc/groups
video:x:33:rtalkad
See /etc/group file format.
How to count total number of lines using shell script..????
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.
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])
@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!!