Techknow Study

grep Command

2:54:00 PM vikas 0 Comments Category : ,

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

“Grep” command is use to search for a given file for line containing some word, string.
By default grep display 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 can run in both linux and unix in their command editors.

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

how to use gre to seach a file?
Search /etc/passwd for vicky user:
$ grep vicky /etc/passwd
You can force grep to ignore word case i.e match Vicky, Vicky, VICKY and all other combination with -i option:
$ grep -i "vicky" /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 vicky, grep will match yovicky, vicky123, etc. You can force grep to select only those lines containing matches that form whole words i.e. match only vicky 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
UNIX / Linux pipes and grep command
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


RELATED POSTS

0 comments