grep faster and more effectively than grep, using grep

May 24, '07 07:30:00AM

Contributed by: boredzo

I see many hints here on Mac OS X Hints that use the grep utility to filter text. However, many of these hints use grep to search for a plain string, rather than a regular expression. There's nothing wrong with that goal, but using grep for that is inefficient (you're invoking the full power of the regex engine just for a plain string), and requires that you escape any regex characters in the pattern:

 grep 'Price: $' partslist.txt
 # Incorrect: Only matches "Price: " at the end of a line

 grep 'Price: $' partslist.txt
 # Correct: Matches "Price: " followed by a dollar sign
There's a better way. grep also exists under the name fgrep, which searches for a fixed (hence the 'f') string -- that is, a plain string; no characters are special. You can search for any string this way, with no escaping needed (see note below):
 fgrep 'Price: $' partslist.txt 
 # Correct: Matches "Price: " followed by a dollar sign
You can also do this with grep -F, but fgrep is shorter. fgrep and grep are the same program, just with different behavior, so all the other options (-n, -o, -H, etc.) are supported by both.

Note: Of course, you may need to escape quotes or backslashes according to the rules of your shell, but you would have to do this anyway. My point is that fgrep does not require quoting where grep itself would.

Comments (12)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20070522102058324