The dangers of grep

Posted by Sysadmin 4 lyfe on September 22, 2014

Grep is a fantastic tool for everyday use in Unix systems and is one of the most highly utilised GNU tools today. However there’s a common mistake I see when used in shell and Perl scripts.

image

Consider the trivial example of the following file:

$ cat /tmp/grep.me
ab
cd
abc

Now lets do a normal grep for just the first line:

$ grep ab /tmp/grep.me
ab
abc

Now when coding shell scripts on the fly it’s quite easy to see our mistake, a partial match on the third line that usually isn’t what we wanted. But when prototyping scripts we may miss this, because abc might be added later.

This is very easily solved and anyone who’s used grep/regex long enough already knows the answer. However it’s common to see even experienced system administrators make this mistake.

$ grep '^ab$' /tmp/grep.me
ab