Thursday, March 15, 2012

GREP command in UNIX!!

The grep  is a very powerfull search command in Unix. It is used to search the string or pattern or regular exression in a file line by line and displays the line which contains the given pattern. grep stands for global regular expression parser or print. The grep family includes grep, egrep, fgrep.

Syntax:

grep [options] pattern filename

grep:   is a orginal command, its basic use to select the line and search for the string
egrep: is Extended grep and it uses extended regular expression (supporting logical OR in pattern) to select the lines to process. 
fgrep: is a Fast grep and it will not use the regular expressions, but it uses string literals to process.

Example for grep:

$grep ^[aeiou] test.txt
in a file line by
or print. The grep family
includes grep, egrep, fgrep
a son of srking.
a son of srqueen .

The above grep command searches for the patterns starting with vowel small letters in the starting of the line in the file test.txt and displays them
 
Example for egrep:
 
$egrep 'jr|sr|super ' test.txt
jrking is
a son of srking.
srking is a son of supersrking.
supersking grand sun is jrking.

$grep 'jr|sr|super ' test.txt
$


The above egrep searches for the strings jr or sr or super in test.txt file. single quotes are mandatory. grep displays nothing as it doesnot support logical OR.
 

Example for fgrep:

$fgrep king test.txt
jrking is
a son of srking.
srking is a son of supersrking.
supersking grand sun is jrking.

$fgrep ^[aeiou] test.txt
$

From the above examples, in the first fgrep  is looking for the string literal 'king' in test.txt and displays the lines which contains the 'king' literal. Where as in second command fgrep is looking for the regular expression ^[aeiou] and it displays nothing as fgrep doesn't support regular expressions. If you use grep  instead of fgrep , you will get the result as shown in example for grep above.

Some of usefull grep options:

-i : ignore the case
-r: search for the pattern recursively (usefull for searching in the directory/sub-directory)
-n: displays the lines with line no.s
-c: displays the count of the found patterns
-l: displays the file name which contains the given pattern (this is usefull while searching in sub-directories)

No comments:

Popular Posts