recursive grep

I am trying to search through all files in a directory tree, perhaps to find a specific function declaration. Ideally I want the exact files and line numbers of every search match.

A modern GNU grep contains a “-r” recursive options, so for example to find the function declaration (with line number) for “authenticate” you would simply type

grep -rn 'function authenticate()' .

Easy, but if you’re not always on a system using a modern GNU grep you may find yourself using the old-school find . exec grep approach

find . -exec grep -n 'function authenticate()' {} /dev/null ;

One advantage to this approach is that ‘find’ supports more interesting filter options so you could limit your search to only certain types of files.

There’s also the xargs approach

find . | xargs grep -n 'function authenticate()'

And lastly there is my absolute favorite, ack.

ack 'function authenticate' .

I love ack because it seems to always do exactly what I want, by default. It uses regular expressions by default, it recurses directories by default, syntax highlighting by default, it ignores directories like CVS and .svn by default, and it includes the filename and line numbers by default. You could do all of that with ‘grep’ and ‘find’ but not by default, and unfortunately not easily.