Sean’s Obsessions

Sean Walberg’s blog

Piping With the Find Command and Dealing With Spaces

I often use the find command as such:

1
grep foo `find . -name \*.php`

which looks for foo in all the PHP files. If the list of files gets too long for the shell, then xargs is the better option:

1
find . -name \*.php | xargs grep foo /dev/null

This breaks up the command into manageable chunks. The /dev/null is there in case xargs only passes one file name to the command, this ensures there will be two file names to trigger the printing of the matching file (there’s probably an option, but I like this way better)

The problem with find -print |xargs is that a file or directory with spaces causes problems. For instance “xxx yyy/blah.php” will run

1
grep foo /dev/null xxx yyy/blah.php

neither of which exist.

My first hack at it was to revert to programmer mode and do a loop:

1
find . -name \*.php | while read A; do grep foo "$A" /dev/null; done

The best solution I found so far is to use -printf to force find to quote the file when it spits out the file name and get back into the xargs/stream mode of thinking:

1
find . -name \*.php -printf '"%h/%f"\n' | xargs grep foo /dev/null

Maybe there’s an easier way? (besides shooting people that use spaces in directory or file names)

Comments

I’m trying something new here. Talk to me on Twitter with the button above, please.