Thursday 20 August 2009

Using find with xargs in Linux/Mac/Unix/Cygwin with spaces in the file paths

I'm always having to perform searches through lots of files when on Mac/Linux/Cygwin

This is the style of command I'd normally use from the bash shell (Terminal) on Mac/Linux/Unix/Cygwin ...


find . -name "*.cpp" | xargs -- grep -i "find me" > q.q


This looks from the current folder (and all files below), searching for all files with the cpp file extension. For every file, it runs grep on it (case insensitively); putting the results of all searches in the file called q.q (which you can then edit using e.g. vim).

However, this simply doesn't work when the file or folder being searched has a space character in it. Which is annoyingly common in a files these days...

A short while back I discovered the solution to this "spaces in names/folders" problem, and I figured it'd be useful to write it up to save you the trouble...


find . -name "*.cpp" -print0 | xargs -0 -- grep -i "find me" > q.q


Note how we've added both -print0 and -0, which together magically solve the problem.

Incidentally, the -- in the argument list for xargs, is shell magic that tells xargs to ignore any options it might see after that point (e.g. the -i in the example), and simply pass them directly on to the command (grep in our example).

No comments: