有没有办法在带有选项exec的find命令中使用If条件?

时间:2016-04-27 19:54:48

标签: bash shell unix find

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

前:

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

我需要包括if条件和find -exec(如果grep为true,则打印上面的内容)

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

谢谢

2 个答案:

答案 0 :(得分:5)

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

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

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

如果条件更复杂,可以将整个shell代码放入脚本中,然后使用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 {} \;

然后执行:

composer update

答案 1 :(得分:0)

由于您在-P中使用了PCRE选项grep,因此您可以使用前瞻将两个搜索结合到一个grep中:

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

顺便说一下你的问题中显示的正则表达式是无效的,我试图在这里纠正它。

相关问题