find | xargs grep: hack of the day

September 5th, 2007

Even with today’s modern IDE’s and plethora of search tools (Spotlight, etc.), I still find myself occasionally dropping to a bash shell to look for something in an unknown file. In the past, I was a bit frustrated that my combination of find | xargs grep would bomb out on any files or directories that included a space. Today it dawned on me that there’s a simple workaround for this… Prefix and postfix each file with a quote via sed. The following example recipe will find the text textIAmSearchingFor in any .java file in the current tree.

find . -name "*.java" | sed 's/^/"/' | sed 's/$/"/' | xargs grep "textIAmSearchingFor" | less

UPDATE: As Nicholas points out in the comments below, there’s an easier more efficient way to do this:

find . -iname "*.java" -print0 | xargs -0 grep -i "SearchString" | less

One Response to “find | xargs grep: hack of the day”

  1. Nicholas Says:

    You can also do it like this:

    find . -iname “*.java” -print0 | xargs -0 grep -i “SearchString” | less

    the -print0 lets find break each result with a NULL character, instead of a space, and the xargs -0 tells it the same.

Leave a Reply

Powered by WP Hashcash