Difference between revisions of "Grep examples"

From thelinuxwiki
Jump to: navigation, search
(Pushed from Themanclub.)
 
 

Latest revision as of 21:03, 23 September 2013

grep for multiple strings:

grep -E "one|two|three"

grep for first pattern match only

grep -m 1 <pattern>

For grepping line-by-line in a file filename, I often find these very useful

Match pattern1 OR pattern2 in the same line:

$ grep -E 'pattern1|pattern2' filename

Match pattern1 AND pattern2 in the same line:

$ grep -E 'pattern1.*pattern2' filename

The above command searches for pattern1 followed by pattern2. If the order does not matter or you want to search them in either order, then use the follwoing

$ grep -E 'pattern1.*pattern2|pattern2.*pattern1' filename

The pipe enables the OR search which we saw earlier. Another option for this situation (i.e., AND search when the order is not important):

$ grep -E 'pattern1' filename | grep -E 'pattern2'

which basically greps the STDOUT of the first grep.

Match pattern1 AND pattern2, but NOT pattern3 in the same line:

$ grep -E 'pattern1.*pattern2' filename | grep -Ev 'pattern3'

when the order of the first two patterns is important. When that order is NOT important:

$ grep -E 'pattern1' filename | grep -E 'pattern2' | grep -Ev 'pattern3'

Match pattern1 OR pattern2, but NOT pattern3 in the same line:

$ grep -E 'pattern1|pattern2' filename | grep -Ev 'pattern3'