我得到了一个包含我要复制的文件名的字符串。但是,这些文件中只有一部分存在。我当前的脚本如下所示:
echo $x | xargs -n 1 test -f {} && cp --target-directory=../folder/ --parents
但是,我总是遇到 test: {}: binary operator expected
错误。
我该怎么做?
最佳答案
您需要向 xargs
提供 -i
标志,以便它用 {}
替换文件名。
但是,您似乎期望 xargs
提供给 cp
,但它没有这样做。也许尝试类似的东西
echo "$x" |
xargs -i sh -c 'test -f {} && cp --target-directory=../folder/ --parents {}'
(还要注意在 echo
中使用双引号。在极少数情况下,您需要一个没有引号的变量插值。)
要一次传入多个文件,可以在 sh -c
中使用 for
循环:
echo "$x" |
xargs sh -c 'for f; do
test -f "$f" && continue
echo "$f"
done' _ |
xargs cp --parents --target-directory=".,/folder/"
_
参数是因为 sh -c
的第一个参数用于填充 $0
,而不是 $@
关于linux - xargs 如果文件存在则复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16775098/