रविवार, जनवरी 14, 2007

Nifty use of grep!!

GREP:
Suppose you want to search for lines containing a line consisting of white space, then the word hello, then the end of the line. Let us start with an example.

>cat file

        hello
hello world
       hhello


>grep hello file

        hello
hello world
       hhello


This is not what we wanted. So what went wrong ? The problem is that grep searches for lines containing the string "hello" , and all the lines specified contain this. To get around this problem, we introduce the end and beginning of line characters

The $ character matches the end of the line. The ^ character matches the beginning of the line.

Examples
returning to our previous example,

grep "^[[:space:]]*hello[[:space:]]*$" file

does what we want (only returns one line) Another example:
grep "^From.*mscharmi" /var/spool/mail/elflord searches my inbox for headers from a particular person. This kind of regular expression is extremely useful, and mail filters such as procmail use it all the tims.

कोई टिप्पणी नहीं:

StatCounter


View My Stats