如何同时运行 find
和 cp
命令?我已经尝试过:
find -name "*pdf*" | xargs cp $1 ./
但是这不起作用。
最佳答案
使用-exec
选项:
find ./ -name "*pdf*" -exec cp -t . {} \+
{}
将替换为当前正在处理的文件名。
来自 find
的手册页:
-exec command {} +
...the command line is built by appending each selected file name at the end.. The command line is built in much the same way that
xargs
builds its command lines.
注意使用-t
(目标目录)选项(这是一个GNU 扩展)。我们不能使用 -exec cp {} 。 +
,因为匹配的文件名被附加到命令行的末尾,而目的地必须最后指定。另一种解决方法是调用 sh
:
find ./ -name "*pdf*" -exec sh -c 'cp "$@" .' '' {} +
我习惯性地转义了+
字符。请注意,您应该转义 find
语法的特殊字符,以防止它们被 shell 扩展。特别是,在 +
之前可能不需要反斜杠,因为大多数 shell 会将其解释为字符串(它不会扩展为不同的内容)。但是,您肯定必须转义/引用 ;
(这会将命令按顺序应用于每个文件):
find -name "*pdf*" -exec cp -f {} . ';'
关于linux - 如何在 Linux 中同时运行 find 和 cp 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40392838/