grep by Example
Syntax: grep 'word' file1 file2 file3
To find all lines containing behnam:
$ grep -i behnam /etc/passwdTo 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.txtTo search 2 different words:
$ egrep -w behnam|behdad test.txtTo 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.txtTo find out how many lines does not match the pattern:
$ grep -v -c behnam test.txtTo display lines starting with the string "root"
$ grep ^root /etc/passwdTo 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 *.txtTo display output in colors:
$ grep --color root /etc/passwdTo search a string in a Gzip compressed file:
$ zgrep –i behnam test.tar.gzTo 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.txtTo 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
<< Home