Using Perl regex for faster grep

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, April 18, 2011

Follow me on Twitter as @mattiasgeniar

Something I’ve only just noticed, but I find it interesting. If it’s already known to you, then be happy. :-)

$ time grep -i 'closing' error_log | wc -l 
real    0m2.144
user    0m2.139s
sys     0m0.011s

The above is with the default grep, using ‘-i’ to search case insensitive.

$ time grep -iP 'closing' error_log | wc -l
real    0m0.104s
user    0m0.095s
sys     0m0.012s

The above uses -P, or the Perl Regular Expressions. In this example, that’s 20x faster than regular grep! You loose that advantage as soon as you search case sensitive, but if you’re a fan of -i, become a fan of -P as well.

Can anyone say alias grep='grep -P' ?



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.