Wednesday, January 28, 2009

Finding stuff in Unixland with Grep or Find

Sometimes you need to find something somewhere in your filesystem. Forget where thought. You remember it was in a PHP file somewhere, though.

The classic way I was taught was with a find -exec {} command:

find . -name "*.php" -exec grep -H "title phonetitle" {} \;

But, in reading the man page for grep, I see it has a -R option, for recursive. So, which is faster? Find or grep?

First, the classic find -exec command. I've suppressed the output from grep for clarity:


[buzzaboutwireless@ad cms]$ time find . -name "*.php" -exec grep -q "title phonetitle" {} \;

real 0m0.657s
user 0m0.182s
sys 0m0.487s


Now, for the recursive grep:


[buzzaboutwireless@ad cms]$ time grep -Rq "title phonetitle" .

real 0m0.251s
user 0m0.083s
sys 0m0.165s


Way faster. Neat. Less typing too.


Next: To prove black is white. I'll just remember to watch out for the zebra crossings.

1 comment:

speedeep said...

If you do go with the old-fashioned find-exec-grep on Solaris, I used to get frustrated that it would print the matched lines, but not the filenames that matched (since each grep is against only one file.) A trick to solve that:

find /path -name pattern -exec grep textstring {} /dev/null \;

Adding /dev/null as a second filename to the grep call makes it print the matched filename.