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

作为了解如何使用管道操作符来控制绑定优先级的手段,我正在尝试打印每个目录下一个文件的路径 - 对于每个目录都是如此。
find $PWD -type d | xargs --delimiter "\n" -I% -n 1 (find % -maxdepth 1 | head -1)

我得到了“没有找到匹配项:(find%-maxdepth 1 | head -1)”。如果没有括号,我会得到“xargs:find:被信号13终止”,所以我很确定我们需要以某种方式使管道成为右结合的。
如何将xargs输入传递给包含管道的命令?(请不要告诉我使用“-exec”,我想学习如何操纵绑定优先级来解决其他问题)。
4个回答

这里是关于xargs的内容。
find . -type d|xargs -I % sh -c 'find % -type f -maxdepth 1 | head -1'

但要记住:内部循环要快得多
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

1有趣。不过,我还是想学习正确的管道关联方式(如果可能的话)。我以为在花括号中创建一个子shell可以解决问题,但显然并不行。 - Sridhar Sarnobat
1你没有其他解决方案,只能使用xargs。请参考:http://stackoverflow.com/questions/6958689/xargs-with-multiple-commands-as-argument - Ipor Sircer
哦,这就是为什么你不喜欢xargs的原因。或者至少,这就是你把我变成一个xargs反对者的原因 :) 任何抛弃了Shell的力量的解决方案都只是昙花一现。 - Sridhar Sarnobat

个人而言,我不喜欢使用xargs。
find $PWD -type d | while read dir;do find $dir -type f -maxdepth 1 | head -1;done

很高兴知道还有这个选择。虽然我讨厌循环;) - Sridhar Sarnobat
你很快会"爱上"循环! ;-> - Ipor Sircer
就算我是一个函数式编程的活动家?在写Java代码时,我尽量避免使用循环。但只要循环只做一件事情,那还是可以接受的,尽管有点啰嗦 :( - Sridhar Sarnobat

这是最快的解决方案,而且一切都是内部的。
time find . -type d | while read dir;do for file in "$dir"/*;do if [ -f "$file" ]; then realpath $file;break;fi;done;done >/dev/null
    0m00.21s real     0m00.08s user     0m00.10s system

无与伦比的速度在shell中。(我说过我不喜欢xargs)

我知道这是一个旧帖子,但是你可以使用bash -c来使用子shell。
find $PWD -type d | xargs --delimiter "\n" -I% -n 1 bash -c 'find % -maxdepth 1 | head -1'

让我解释一下:bash -c 生成一个子shell,它接受一个字符串参数,这个参数在这种情况下是find命令。作为一个子shell,你可以使用任何你喜欢的命令,只要记住这个命令是在一个字符串中,并且子shell可能有不同于父shell的环境。

1有没有办法在不使用引号的情况下完成这个命令?我不喜欢使用引号的原因之一是,无法将这样的命令跨越多行编写,也无法正确显示语法高亮。 - Sridhar Sarnobat

  • 相关问题