Xargs 将输入传递给包含管道的命令

Sri*_*bat 11 xargs pipe

作为了解如何使用管道操作绑定优先级的一种工具,我试图为每个目录打印一个文件的路径:

find $PWD -type d | xargs --delimiter "\n" -I% -n 1 (find % -maxdepth 1 | head -1)
Run Code Online (Sandbox Code Playgroud)

我明白了no matches found: (find % -maxdepth 1 | head -1)。没有括号我会得到xargs: find: terminated by signal 13所以我很确定我们需要以某种方式使管道右关联。

如何将 xargs 输入传递给包含管道的命令?(请不要告诉我使用-exec,我想学习如何操作其他问题的绑定优先级)。

Ipo*_*cer 11

在这里,您可以使用 xargs:

find . -type d|xargs -I % sh -c 'find % -type f -maxdepth 1 | head -1'
Run Code Online (Sandbox Code Playgroud)

但请记住:内部循环快得多!

time find $PWD -type d | while read dir;do find $dir -type f -maxdepth 1 | head -1;done >/dev/null                                                                                       
    0m09.62s real     0m01.67s user     0m02.36s system
time find . -type d|xargs -I % sh -c 'find % -type f -maxdepth 1 | head -1' >/dev/null                                                                                                   
    0m12.85s real     0m01.84s user     0m02.86s system
Run Code Online (Sandbox Code Playgroud)