Blogs Directory

Monday, April 15, 2013

'grep' command to match only the words in a text file

While i was doing my usual office work i got a situation where i need to get the list of words that match a pattern from a text file. After many google searches and man page reads i found the solution. Let this help someone else who gets into the same situation of mine.

grep : usually greps lines containing the pattern

-o : option specifying to match only the part of the line that matches the PATTERN

Example : 

grep -o PATTERN file_name

PATTERN here can be any regular expression also. Use -P for specifying perl regular expressions. 

Example : 

grep -o -P mr_.*_sad file_name

to match the words 

1. mr_harish_is_sad
2. mr_suresh_is_great

No comments :

Post a Comment