【问题标题】:How to combine two commands in -exec parameter of find?如何在find的-exec参数中组合两个命令?
【发布时间】:2016-10-20 08:03:28
【问题描述】:

我有这个 find 命令来获取过去 50 秒内修改的所有文件,这些文件与最后 1000 个字符中的以下正则表达式 hell\d 匹配。 我使用 tail 获取最后 1000 个字符以加快搜索速度,因为要检查的文件很大(平均 3gb)。

find /home/ouhma -newermt '50 seconds' -type f |
while read fic; do
    if tail -c 1000 "${fic}" | LANG=C LC_ALL=C grep -Pq 'hell\d'; then
        echo "${fic}"
    fi
done

是否可以使用-exec 参数来替换那个丑陋的循环并更快地检索结果?

这可行,但我不知道这是不是最好的方法:

find /home/ouhma -newermt '50 seconds' -type f -exec bash -c 'LANG=C LC_ALL=C grep -Pq "hell\d" <(tail -c 1000 "{}") && echo "{}"' \;

【问题讨论】:

    标签: bash grep find exec xargs


    【解决方案1】:

    多个-exec动作可以相互跟随,如果前一个-exec成功,则将运行一个-exec,即-exec运行的命令返回退出状态0。

    做:

    find /home/ouhma -type f -newermt '50 seconds' -exec env LC_ALL=C \
           bash -c 'grep -Pq "hell\d" <(tail -c 1000 "$1")' _ {} \; -exec echo {} \;
    

    当您只是打印文件名时,这就足够了:

    find /home/ouhma -type f -newermt '50 seconds' -exec env LC_ALL=C \
           bash -c 'grep -Pq "hell\d" <(tail -c 1000 "$1") && echo "$1"' _ {} \;
    

    【讨论】:

    • 如果我用这种方式测试你的命令:find /home/ouhma/hello.txt -exec LC_ALL=C grep -Pq 'hell\d' &lt;(tail -c 1000 {}) \; -exec echo {} \; 它返回以下错误:tail: cannot open '{}' for reading: No such file or directory find: 'LC_ALL=C': No such file or directory
    • 为每个文件生成一个bash 不会比 OP 自己的尝试快。
    • @anubhava 是的,现在检查。
    • 很好,但现在它将扫描完整的 3GB 数据,而不仅仅是最后 1000 个字符。
    • @anubhava Hmmm..chicken-egg 问题我看到了:/
    猜你喜欢
    • 1970-01-01
    • 2015-03-06
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    相关资源
    最近更新 更多