xargs – How to Handle Spaces in File Names When Using xargs on Find Results

findgreppipexargs

One of my common practices is to perform greps on all files of a certain type, e.g., find all the HTML files that have the word "rumpus" in them. To do it, I use

find /path/to -name "*.html" | xargs grep -l "rumpus"

Occasionally, find will return a file with a space in its name such as my new file.html. When xargs passed this to grep, however, I get these errors:

grep: /path/to/bad/file/my: No such file or directory
grep: new: No such file or directory
grep: file.html: No such file or directory

I can see what's going on here: either the pipe or the xargs is treating the spaces as delimiters between files. For the life of me, though, I can't figure out how to prevent this behavior. Can it be done with find + xargs? Or do I have to use an entirely different command?

Best Answer

Use

find ... -print0 | xargs -0 ...

e.g.

find /path/to -name "*.html"  -print0 | xargs -0  grep -l "rumpus"

from the find man page

-print0
          True; print the full file name on the standard  output,  followed
          by  a  null  character  (instead  of  the  newline character that
          ‘-print’ uses).  This allows file names that contain newlines  or
          other  types  of  white space to be correctly interpreted by pro-
          grams that process the find output.  This option  corresponds  to
          the ‘-0’ option of xargs.
Related Topic