Recursive Greps

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.

This entry was posted in General. Bookmark the permalink.

6 Responses to Recursive Greps

  1. Nic says:

    Why not just use the much faster grep-ack? http://betterthangrep.com/

    • jcs jcs says:

      Probably for the same reason that I didn't know about the --include option. I learned to use grep very 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 consider grep-ack but for my quotidian use of grep it doesn't seem worth the trouble.

  2. Xah Lee says:

    Thanks! Been frustrated with this.

    is the --include new in past few years, or ancient in GNU grep?

    • jcs jcs says:

      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.

  3. Rick Richmond says:

    Never knew this, I've been doing the following to similar effect for years:

    find -name "*.c"¦ xargs grep foo

Comments are closed.