Using find with xargs: dealing with spaces in paths

One useful command line “pattern” is using find and xargs together. For example, to search for instances of “banana” in a folder hierarchy containing text files, one can do this:

find . -name "*.txt" | xargs grep banana

If the paths contain spaces, this will fail because xargs by default uses spaces as delimiters. For example, a path ./folder1/OS Foo/someFile.txt will yield this error:

grep: ./folder1/OS: No such file or directory
grep: Foo/someFile.txt: No such file or directory

The solution is to use find’s -print0 argument, in conjunction with xarg’s -0  argument:

find . -name "*.txt" -print0 | xargs -0 grep banana

Used like this, find outputs the path with a terminating ASCII NUL character, and xargs uses NUL as a delimiter, so paths with spaces no longer cause problems