带有逻辑运算符的 grep

30 grep

是否有类似 grep 的实用程序可以让我使用逻辑运算符进行 grep 搜索。我希望能够自由地嵌套和组合逻辑结构。例如,这样的事情应该是可能的:

grep (term1 && term2) || (term1 && (term3 xor term4)) *
Run Code Online (Sandbox Code Playgroud)

我意识到这可以通过 vanilla grep 和额外的 bash 脚本来完成,但我的目标是避免这样做。

Thu*_*shi 53

有很多方法可以使用grep逻辑运算符。

  1. 使用 \|为分隔多个模式或状态。

    例子: grep 'pattern1\|pattern2' filename

  2. 使用该-E选项为OR 条件发送多个模式。

    例子: grep -E 'pattern1|pattern2' filename

  3. 使用单个-e只匹配一个模式,但使用多个 -e选项匹配多个模式。

    例子: grep -e pattern1 -e pattern2 filename

  4. grep -v可以模拟NOT操作。

  5. 中没有AND运算符grep,但您可以使用该选项蛮力模拟AND-E。

    例子 : grep -E 'pattern1.*pattern2|pattern2.*pattern1' filename

    上面的示例将以任一顺序匹配包含pattern1和pattern2 的所有行 。)

  • `grep foo | grep bar` 是一种更通用的 AND 方式。 (3认同)
  • `-E` 并不完全等同于 `&&`,因为它是顺序敏感的 (2认同)
  • +1 清楚地解释了没有真正的“AND”运算符,我们能做的最好的事情就是使用 OR 结构模拟黑客攻击。这当然会在超过 3 个术语时变得笨拙,但对于两个术语,它运作良好。 (2认同)

mur*_*uru 14

使用awk,与使用 一样perl,您必须将条款包裹在 中//,但可以这样做:

awk '(/term1/ && /term2/) || (/term1/ && xor(/term3/, /term4/))' 
Run Code Online (Sandbox Code Playgroud)


mic*_*has 6

你可以使用 perl:

perl -wne 'print if (/term1/ && /term2/) || (/term1/ && (/term3/ xor /term4/))'
Run Code Online (Sandbox Code Playgroud)

其中开关如下:

-w turns on warnings
-n runs perl against each line of input (looping)
-e executes perl passed in the command line
Run Code Online (Sandbox Code Playgroud)