Unix Find Xargs And No Such File Or Directory

A useful command that I frequently use when looking for a particular string in a file is a find command piped to xargs grep. For example, if I am looking for the word Mike in any file inside of /usr/local I will type:

find /usr/local -type f | xargs grep Mike

This says to start in the directory of /usr/local and search recursively for anything that is a file. Then pass that file to grep to search inside the file for the text Mike. There is one problem with this though. It doesn’t handle spaces in file names. When it comes across a file name with a space you will usually see something like:

grep: /Someplace/Somewhere: No such file or directory

This can be confusing since you would assume that find actually found something to pass to grep. It is misleading though, as the problem actually has to do with a white space character in the file name or directory. It is very common to see spaces on Linux and Mac OS X systems, so it is important to learn to work around this problem. The solution is pretty simple. Both GNU find and xargs support a zero option that displays white space as a NUL character.

find /usr/local -type f -print0 | xargs -0 grep Mike

This should take care of the white space issues. I hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>