/etc insider

since 1999 (and still editing)

Prefer fgrep instead of grep

| Comments

People tend to get used to something and then the habbits rule them. You’re probably a heavy grep user, aren’t you? You can find grep in lots of one-liners, code snippets and so on. But do you really typically need its ability to search with regular expressions? Not that often I can assume. Meanwhile fgrep is just typically faster, so when you’re greping through some heavy log-file you’re wasting time and CPU cycles. Time is more important, usually. Say you want to find a string which includes dots, but not in the meaning of “any character”, just dot. Let’s see:

1
2
try# time grep no.ImSure.Theres.NoSuch.AString.Inside huge.log
grep no.ImSure.Theres.NoSuch.AString.Inside huge.log  1.05s user 0.27s system 99% cpu 1.333 total

Now let’s try fgrep:

1
2
try# time fgrep no.ImSure.Theres.NoSuch.AString.Inside huge.log
fgrep no.ImSure.Theres.NoSuch.AString.Inside huge.log  0.35s user 0.23s system 99% cpu 0.590 total

– whoa. Two times faster! What if you decided to be fair with grep and told it the dots are just dots, not “any char”(?):

1
2
try# time grep no\.ImSure\.Theres\.NoSuch\.AString\.Inside huge.log                                                                                                                            
grep no\.ImSure\.Theres\.NoSuch\.AString\.Inside huge.log  1.04s user 0.25s system 99% cpu 1.302 total

– it’s still slow. And once again let’s run fgrep just to memorize that if you don’t need regular expression search then you shoud use proper tool for it – fgrep and you should expect your CPU to be used more effectively, saving your time:

1
2
try# time fgrep no.ImSure.Theres.NoSuch.AString.Inside huge.log                                                                                                                                
fgrep no.ImSure.Theres.NoSuch.AString.Inside huge.log  0.33s user 0.26s system 99% cpu 0.597 total

P.S. It’s quite obvious, but still may be forgotten that grep for an IP-addess with un-escaped dots is asking for trouble cause 10.1.2.3 would match 10.192.34.56 too. fgrep would do better but not ideal to – it’s false-hit area is narrow but still not zero-wide: 110.1.2.33 is an example.

Comments