Wednesday, August 27, 2008

grep

grep command is used to search patterns in files.
eg: when we want to find lines with the word 'apple' we can use
grep apple filename
This can also do using
cat filename | grep apple
grep -l gives the file name that has the required pattern. As example if we want to find the name of text file that contains apple,
grep -l apple *.txt

If we use
cat filename | grep -l apple
command gives "stdin", because pipe doesn't know anything about where input is coming from.

grep -i
makes grep command case insensitive.

grep -w command only give the matching of whole word.

grep -c
gives the number of lines those matches with required pattern.

If we want to do invert of particular command, we can use
grep -v apple filename

Two grep commands can make logical and operator.
eg:
grep apple filename | grep banana filename
this command matches both apple and banana

If we want to find the sentences start with "My"
grep ^My filename

The command
grep me$ filename gives the sentences end with me in the file.

Make Logical OR operator
egrep operator is used to expand the capabilities of grep operator. egrep operator can work with logical OR using '|'.
eg:
egrep 'apple | banana' filename

No comments: