【问题标题】:How to use pipe within -exec in find如何在find的-exec中使用管道
【发布时间】:2014-03-16 12:45:12
【问题描述】:

有没有办法在 find 的 -exec 中使用管道?我不希望 grep 遍历整个文件,而只遍历每个文件的第一行。

find /path/to/dir -type f -print -exec grep yourstring {} \;

我尝试用“cat”和“head -1”将管道放在那里,但效果不佳。我试图以某种方式使用括号,但我没有设法弄清楚如何将它们放在那里。 我会非常感谢你的帮助。我知道如何在不使用 find 的情况下以其他方式解决它,但是我们尝试在学校使用 find 和管道来完成它,但无法管理如何去做。

find /path/to/dir -type f -print -exec cat {} | head -1 | grep yourstring \;

这就是我们试图做到的方式,但无法管理括号,甚至可能。我试图通过网络查看,但找不到任何答案。

【问题讨论】:

标签: unix find exec pipe


【解决方案1】:

为了能够使用管道,您需要执行 shell 命令,即带有管道的命令必须是 -exec 的单个命令。

find /path/to/dir -type f -print -exec sh -c "cat {} | head -1 | grep yourstring" \;

注意以上是猫的无用用法,可以写成:

find /path/to/dir -type f -print -exec sh -c "head -1 {} | grep yourstring" \;

实现你想要的另一种方法是说:

find /path/to/dir -type f -print -exec awk 'NR==1 && /yourstring/' {} \;

【讨论】:

    【解决方案2】:

    这并不能直接回答您的问题,但如果您想做一些复杂的操作,您最好编写脚本:

    for file in $(find /path/to/dir -type f); do echo ${file}; cat $file | head -1 | grep yourstring; done

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-19
    • 2015-10-28
    • 1970-01-01
    • 2018-03-06
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多