【问题标题】:Is there way to use If condition inside a find command with option exec?有没有办法在带有选项 exec 的 find 命令中使用 If 条件?
【发布时间】:2016-04-27 19:54:47
【问题描述】:

场景:一个文件夹中有多个文件,我正在尝试查找特定的文件集,如果给定文件具有特定信息,那么我需要 grep 信息。

例如:

find /abc/test \( -type f -name 'tst*.txt' -mtime -1 \) -exec grep -Po '(?<type1).*(?=type1|(?<=type2).*(?=type2)' {} \;

我需要在 find -exec 中包含 if 条件(如果 grep 为真,则打印以上内容)

if grep -q 'case=1' <filename>; then
    grep -Po '(?<type1).*(?=type1|(?<=type2).*(?=type2)'
fi

谢谢

【问题讨论】:

  • 所以需要单独处理每个文件?

标签: bash shell unix find


【解决方案1】:

您可以在find 中使用-exec 作为条件——如果命令返回成功的退出代码,则文件匹配。所以你可以写:

find /abc/test -type f -name 'tst*.txt' -mtime -1 -exec grep -q 'case=1' {} \; -exec grep -Po '(?<type1).*(?=type1|(?<=type2).*(?=type2)' {} \;

find 中的测试是从左到右评估的,因此第二个 grep 只有在第一个成功时才会执行。

如果你的条件比较复杂,可以把整个shell代码写成一个脚本,用-exec执行脚本。例如。把这个放在myscript.sh:

#!/bin/sh
if grep -q 'case=1' "$1"; then
    grep -Po '(?<type1).*(?=type1|(?<=type2).*(?=type2)' "$1";
fi

然后做:

find /abc/test -type f -name 'tst*.txt' -mtime -1 -exec ./myscript.sh {} \;

【讨论】:

  • 可能会在 shell 脚本中迭代 "$@" -- 然后你可以使用 -exec ./myscript {} + 并减少调用次数。也可以在两个 exec 方法的右侧执行相同的操作。
  • 是的,我试图让答案保持简单。
【解决方案2】:

由于您在 grep 中使用 PCRE 选项 -P,您可以将两个搜索合并为一个 grep 以及使用前瞻:

find /abc/test -type f -name 'tst*.txt' -mtime -1 -exec grep -Po '(?=.*case=1).*\K((?<=type1).*(?=type1)|(?<=type2).*(?=type2))' {} +

顺便说一句,您的问题中显示的正则表达式无效,我已尝试在此处进行更正。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多