简体   繁体   English

如果文件存在,则xargs复制

[英]xargs copy if file exists

I got a string with filenames I want to copy. 我收到了一个包含我要复制的文件名的字符串。 However, only some of these files exist. 但是,只存在其中一些文件。 My current script looks like this: 我当前的脚本如下所示:

echo $x | xargs -n 1 test -f {} && cp --target-directory=../folder/ --parents

However, I always get a test: {}: binary operator expected error. 但是,我总是得到一个test: {}: binary operator expected错误。

How can I do that? 我怎样才能做到这一点?

You need to supply the -i flag to xargs for it to substitute {} for the filename. 您需要为xargs提供-i标志,以便用{}替换文件名。

However, you seem to expect xargs to feed into the cp , which it does not do. 但是,您似乎期望xargs能够提供给cp ,而它并没有这样做。 Maybe try something like 也许尝试类似的东西

echo "$x" |
xargs -i sh -c 'test -f {} && cp --target-directory=../folder/ --parents {}'

(Notice also the use of double quotes with echo . There are very few situations where you want a bare unquoted variable interpolation.) (也注意与使用双引号的echo 。有你想要裸不带引号的变量替换情形是很少见。)

To pass in many files at once, you can use a for loop in the sh -c : 要一次传入许多文件,可以在sh -c使用for循环:

echo "$x" |
xargs sh -c 'for f; do
    test -f "$f" && continue
    echo "$f"
done' _ |
xargs cp --parents --target-directory=".,/folder/"

The _ argument is because the first argument to sh -c is used to populate $0 , not $@ _参数是因为sh -c的第一个参数用于填充$0 ,而不是$@

xargs can only run a simple command. xargs只能运行一个简单的命令。 The && part gets interpreted by the shell which is not what you want. &&部分由shell解释,这不是你想要的。 Just create a temporary script with the commands you want to run: 只需使用您要运行的命令创建临时脚本:

cat > script.sh
test -f "$1" && cp "$1" --target-directory=../folder/ --parents

Control-D 控制-d

chmod u+x ./script.sh
echo $x | xargs -n1 ./script.sh

Also note that {} is not needed with -n1 because the parameter is used as the last word on a line. 另请注意, -n1不需要{} ,因为该参数用作一行的最后一个单词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM