I’ve been using the Unix grep utility for over 20 years but today I learned something new. Mikko Ohtamaa over at Open Source Hacker has a nice post on Power searching using UNIX grep. The post explores some of the enhancements to the GNU version of grep. These days, even Mac OS X comes with GNU grep so it’s a worthwhile read.
One of the things you often to do with grep is to search recursively into subdirectories but the older versions had no way of filtering on file type. Thus, you could say something like
grep -R foo ~/projects
to search through the projects subtree but there was no way to specify which files you wanted to consider. If there were binary files under the projects subdirectory you would search them too. Fortunately, GNU grep has a way around this. If we want to search just C files we would specify something like
grep -R --include="*.c" foo ~/projects
It’s hard to believe that I didn’t know about this after all the time I’ve been using grep. My only defense is that I learned grep early on and had little reason to revisit the documentation. In any event, it’s comforting to know that my education is ongoing.
Why not just use the much faster grep-ack? http://betterthangrep.com/
Probably for the same reason that I didn’t know about the
--includeoption. I learned to usegrepvery early in my career and it was always good enough to get the job done. If I were still involved with large projects having huge code bases, I would probably considergrep-ackbut for my quotidian use ofgrepit doesn’t seem worth the trouble.Thanks! Been frustrated with this.
is the –include new in past few years, or ancient in GNU grep?
I don’t know. As I said in the post, I’m just now learning about it. If any readers have some wisdom on this, leave a comment.
Never knew this, I’ve been doing the following to similar effect for years:
find -name “*.c”¦ xargs grep foo
Yup. That’s exactly what I did too.