Tuesday, October 9, 2012

Regular Expresion using Linux Grep

Linux grep command is commonly used when we need to filter a file or string. The advantage of grep would be maximized when combined use extended regular expression with the option E. Following are some good example to give you some inspiration:

Find a line contains the word "team"
$echo "we are in a team in US."|grep -E '\bteam\b'
$we are in a team in US.

This regular expression is equivalent to grep -E -w 'team' with the option w.

Note:
\b means the boundary of the word, it doesn't consume any character of the string.
see difference of basic regular expression and extended regular expression

A tricky thing here is: if the string contain "teams" or "team!" with a exclamation mark. The above regular expression will not match.

if we can change the regular expression to '\bteam'
$echo "we are teams in US."|grep -E '\bteam'
$we are in a team in US.

No comments:

Post a Comment