Uses Of Grep Command In Unix And Linux Servers

February 29, 2012 / Dedicated Servers Linux

Uses Of Grep Command In Unix And Linux Servers

The name, “grep” is indicative of the operation which this command performs. It is executed 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'
command option1 | grep'data'
grep --color 'data' fileName

* Way To Search File With grep Command :

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

Users can force grep to ignore word case. Such as, match boo, Boo, BOO and another combination with -i option:
$ grep -i "boo" /etc/passwd

* Utilize grep Recursively

User can search recursively. Such as, read all files under each directory for a string “192.168.2.6”
$ grep -r "192.168.2.6" /etc/

* Way To Search Words With grep Command :

When the user searches for boo, grep will match fooboo, boo123, etc. Grep can be made to select only the lines which contain matching whole words such as only the word boo.

$ grep -w "boo" /path/to/file

* Way To Search Two Different Words with grep command :

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

*Way To Count Lines Content Similar Words With grep Command:

Users can get the number of times which the pattern has been matched for every file with -c (count) option:
$ grep -c 'word' /path/to/file
Also keep in mind that the user can utilize -n option, which causes grep to precede every 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

The -v option is used to print inverts of the match; meaning that it will return only those lines that do not contain the given word. For example, print all lines that do not contain the word bar
$ grep -v bar /path/to/file

* grep Command With Pipes

grep command is also used with pipes. As follows :
# dmesg | egrep '(s|h)d[a-z]'
Display cpu model name:
# cat /proc/cpuinfo | grep -i ‘Model’
Users can use the above command without a shell pipe, like below :
# grep -i 'Model' /proc/cpuinfo

* Way to list out the name of the matching files :

Use the -l option to list file names whose contents mention main():
$ grep -l 'main' *.c
Users can also force grep to display output in colors:
$ grep --color vivek /etc/passwd

Leave a Reply

Your email address will not be published. Required fields are marked *