Tuesday, June 16, 2015

grep by Example


Syntax: grep 'word' file1 file2 file3

To find all lines containing behnam:
$ grep -i behnam /etc/passwd
To search recursively i.e. read all files under /etc:
$ grep -r 192.168.1.5 /etc/
To search only behnam not behnamp:
$ grep -w behnam test.txt
To search 2 different words:
$ egrep -w behnam|behdad test.txt
To report the number of times that the pattern has been matched:
$ grep -c behnam test.txt

To precede each line of output with the number of the line in the file:
$ grep -n root /etc/passwd

Tp print all lines that do not contain behnam:
$ grep -v behnam test.txt
To find out how many lines does not match the pattern:
$ grep -v -c behnam test.txt
To display lines starting with the string "root"
$ grep ^root /etc/passwd
To filter the name of the hard disk partitions in dmesg output: 
$ dmesg | egrep "(s|h)d[a-z][1-9]"

Note: The above example does not work with grep and as you see we used egrep instead. egrep is nothing but grep -E which switches grep into a special mode so that the expression is evaluated as an Extended Regular Expression as opposed to its normal pattern matching.

To list text files whose contents mention behnam:
$ grep -l behnam *.txt
To display output in colors:
$ grep --color root /etc/passwd
To search a string in a Gzip compressed file:
$ zgrep –i behnam test.tar.gz
To see which accounts have no shell assigned
$ grep :$ /etc/passwd

To display all words starting with b and ending in m:
$ grep '\<b.*m\>' test.txt
To display the lines which does not match 2 or more patterns: 
$ grep -v -e "pattern 1" -e "pattern 2"
To show the position of match:
$ grep -o -b root /etc/passwd

Labels: ,