linux - 我找到了一种使用 find -exec 将多个文件集中在一行中的方法,如 xargs,但我不确定它到底是如何工作的

标签 linux bash unix find

我一直在使用 find -exec 和 find | xargs 在过去几个小时的探索和试验中,现在我发现了我在其他任何地方都没有见过的命令变体。

例如这个find命令获取子目录中的所有文件并将它们复制到当前目录

find . -type f -regex './[^\.].*/[^.*].*' -exec sh -c 'cp "$@" .' thiscanbeanything {} +

都会像这样在一行上执行:

cp ./testy/bar ./testy/baz ./testy/foo .

而不是通常的:

find . -type f -regex './[^\.].*/[^.*].*' -exec sh -c 'cp {} .' \;

多行执行

cp ./testy/bar .
cp ./testy/baz .
cp ./testy/foo .

此外,在第一个命令中,输出将仅为:

cp ./testy/baz ./testy/foo .

除非 sh -c 'cmd' 后跟其他内容,在我的示例中是 thiscanbeanything.

有人可以阐明发生了什么,或者这是否可行?

最佳答案

要了解发生了什么,请看一下:

$ sh -c 'echo 0=$0 1=$1 2=$2' thiscanbeanything one two
0=thiscanbeanything 1=one 2=two

这将使用选项 -c 'echo 0=$0 1=$1 2=$2' 和三个参数 thiscanbeanything one two 执行 sh .

通常,$0 是正在执行的脚本的名称。运行 sh -c 时,没有脚本,但名称取自您提供的第一个参数,在本例中为 thiscanbeanything

文档

此行为记录在 man bash-c 选项下:

-c string
If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.

关于linux - 我找到了一种使用 find -exec 将多个文件集中在一行中的方法,如 xargs,但我不确定它到底是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28599690/

相关文章:

Linux:哪些程序正在访问 Internet?

基于 TCL 的 Expect 的 Ruby 版本?

bash - ANSI 转义码序列 "ESC[>c"是什么?

bash 脚本 - 如何将逗号分隔列表作为函数的输入参数进行处理

linux - 删除几乎没有差异的重复行

python - 带有回调到 python VM 的 pthread

linux - 使用 awk 替换列

linux - 如何使用 bash 脚本在日期/时间和另一个日期/时间之间提取日志

python - 如何使用子进程停止由单个脚本生成的所有子进程

bash - 在 bash 中的循环内为数组的元素赋值