Sunday, December 2, 2012

HowTo: Use grep Command In Linux / UNIX [ Examples ]



How do I use grep command in Linux and Unix like operating systems? Can you give me a simple example of grep command?

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

grep Command Syntax
The name, "grep", derives from the command used to perform a similar operation, using the Unix/Linux text editor ed:
g/re/p
grep 'word' filename
grep 'string1 string2'  filename
cat otherfile | grep 'something'
command | grep 'something'
command option1 | grep 'data'
grep --color 'data' fileName

How Do I 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
Sample outputs:
Grep command in action
Grep command in action

If you enjoyed the grep tutorial, then you might like to read our "Regular Expressions in Grep" tutorial.

No comments:

Post a Comment