Search for a String Pattern in a File with egrep

The Unix command egrep gives you different options for searching for strings in files than grep.

You can have a pattern in single quotes after the egrep command. This pattern in quotes can contain the | symbol for inclusive OR. So you can look for the string "rock" or "paper" in the file stuff.txt with the pattern 'rock|paper' after the egrep command, like this:

$ cat stuff.txt
rock + paper
scissors
fish
sand + rock
paper + paper + scissors
roll +rock
$ egrep 'rock|paper' stuff.txt
rock + paper
sand + rock
paper + paper + scissors              
roll +rock
$ 

You can also use the special symbol ^ to stand for the beginning of the line or the symbol $ to stand for the end of the line. So we can find all lines that have rock at the immediate start OR lines that have rock immediately preceeding the end of the line like this:

$ egrep '^rock|rock$' stuff.txt
rock + paper
sand + rock
roll +rock
$ 

You can use the backslash \ to allow you to search for characters that otherwise have a special meaning for egrep. For example, we can search for the + sign in the stuff.txt file by putting a \ before the + like this:

$ egrep '\+' stuff.txt
rock + paper
sand + rock
paper + paper + scissors
roll +rock                          
$

The egrep command also supports the handy -w option to search for a string in a file as a word (that is, where it appears alone, with just non-letters before or after it). For example:

$ cat box7.txt
hamhocks + peas
ham sandwiches
gotham, new york + beans
ham+cheese
ham
anna=ham                         
$ egrep -w ham box7.txt
ham sandwiches
ham+cheese
ham
anna=ham
$
Save this page to any social bookmarking site! Share · Search · Market · Directory
2013-04-10 · John December · Contact · Terms of Use © December Communications, Inc.