I'm trying to copy a bunch of files below a directory and a number of the files have spaces and single-quotes in their names. When I try to string together find
and grep
with xargs
, I get the following error:
find .|grep "FooBar"|xargs -I{} cp "{}" ~/foo/bar
xargs: unterminated quote
Any suggestions for a more robust usage of xargs?
This is on Mac OS X 10.5.3 (Leopard) with BSD xargs
.
This is more efficient as it does not run "cp" multiple times:
I used Bill Star's answer slightly modified on Solaris:
This will put quotes around each line. I didn't use the '-l' option although it probably would help.
The file list I was going though might have '-', but not newlines. I haven't used the output file with any other commands as I want to review what was found before I just start massively deleting them via xargs.
If find and xarg versions on your system doesn't support
-print0
and-0
switches (for example AIX find and xargs) you can use this terribly looking code:Here sed will take care of escaping the spaces and quotes for xargs.
Tested on AIX 5.3
find . -print0 | grep --null 'FooBar' | xargs -0 ...
I don't know about whether
grep
supports--null
, nor whetherxargs
supports-0
, on Leopard, but on GNU it's all good.Be aware that most of the options discussed in other answers are not standard on platforms that do not use the GNU utilities (Solaris, AIX, HP-UX, for instance). See the POSIX specification for 'standard' xargs behaviour.
I also find the behaviour of xargs whereby it runs the command at least once, even with no input, to be a nuisance.
I wrote my own private version of xargs (xargl) to deal with the problems of spaces in names (only newlines separate - though the 'find ... -print0' and 'xargs -0' combination is pretty neat given that file names cannot contain ASCII NUL '\0' characters. My xargl isn't as complete as it would need to be to be worth publishing - especially since GNU has facilities that are at least as good.
This method works on Mac OS X v10.7.5 (Lion):
I also tested the exact syntax you posted. That also worked fine on 10.7.5.