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

Nifty use of 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 world

>grep hello file

hello world

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.

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.

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


View My Stats