Saturday, February 6, 2010

Regular Expressions - 1

Regular expressions by practice

I want to search for my name in a large text file. This is a case where we can use simple regular expressions.

egrep Parag file.txt

Will search the file called file.txt and print all lines which have the word 'Parag' in it. But normally things are not as simple as this. What if I suddenly remember that some instances of Parag may not have the first character in upper case. I want to search for all instances of 'Parag', or 'parag'. So basically I want to search for a word which begins with either 'P', or 'p', followed by 'arag'. How do I specify 'P', or 'p'? It can be done with what is known as character classes. A character class essentially results in a match when anythin specifed in a character class matches.

egrep [Pp]arag file.txt

will print all lines containing 'Parag' or 'parag'

No comments: