How can I use xargs to copy files that have spaces and quotes in their names?

后端 未结 22 1126
春和景丽
春和景丽 2020-12-02 03:49

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

22条回答
  •  暖寄归人
    2020-12-02 04:20

    Just don't use xargs. It is a neat program but it doesn't go well with find when faced with non trivial cases.

    Here is a portable (POSIX) solution, i.e. one that doesn't require find, xargs or cp GNU specific extensions:

    find . -name "*FooBar*" -exec sh -c 'cp -- "$@" ~/foo/bar' sh {} +
    

    Note the ending + instead of the more usual ;.

    This solution:

    • correctly handles files and directories with embedded spaces, newlines or whatever exotic characters.

    • works on any Unix and Linux system, even those not providing the GNU toolkit.

    • doesn't use xargs which is a nice and useful program, but requires too much tweaking and non standard features to properly handle find output.

    • is also more efficient (read faster) than the accepted and most if not all of the other answers.

    Note also that despite what is stated in some other replies or comments quoting {} is useless (unless you are using the exotic fishshell).

提交回复
热议问题