bash - 带正负过滤的多行 grep

标签 bash ubuntu grep gnome-terminal

我需要对不包含一个字符串但包含其他字符串的多行字符串进行 grep。这是我在一些 HTML 文件中搜索的内容:

<not-this>
   <this> . . . </this>
</not-this>

换句话说,我想查找包含 <this> 的文件。和 </this>在同一行,但不应被 html 标签包围 <not-this>在之前和/或之后的行上。这是我想做的一些速记逻辑:
grep 'this' && '/this' && !('not-this')
我已经看到以下答案...
grep -Er -C 2 '.*this.*this.*' . | grep -Ev 'not-this'
...但这只会删除包含“非”部分的行,并显示其他行。我想要的是,如果在“this”的一两行中找到“not-this”,它根本不会提取这些结果。

有没有办法做到这一点?

附言我正在使用 Ubuntu 和 gnome 终端。

最佳答案

听起来像 awk脚本在这里可能会更好:

$ cat input.txt
<not-this>
   <this>BAD! DO NOT PRINT!</this>
</not-this>

<yes-this>
   <this>YES! PRINT ME!</this>
</yes-this>


$ cat not-this.awk
BEGIN {
  notThis=0
}

/<not-this>/        {notThis=1}
/<\/not-this>/      {notThis=0}
/<this>.*<\/this>/  {if (notThis==0) print}

$ awk -f not-this.awk input.txt
   <this>YES! PRINT ME!</this>

或者,如果您愿意,可以挤压 awk将脚本写成一行:
$ awk 'BEGIN {notThis=0} /<not-this>/ {notThis=1} /<\/not-this>/ {notThis=0} /<this>.*<\/this>/ {if (notThis==0) print}' input.txt

关于bash - 带正负过滤的多行 grep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22774478/

相关文章:

bash - Docker-Container内jHipster中的Maven包装器:FileNotFoundException

bash - 有没有办法在 bash 中实现一个计数器而不是字母而不是数字?

c++ - 即使我安装了正确的 libprotoc 版本,也会看到 libprotobuf FATAL 错误

grep - 如何一次grep两种模式

linux - 显示以 1 或 0 结尾的所有行,并且 1 位于该行倒数第三个字符

bash - 用sed批量删除多个文件中的多行

linux - 试图删除子目录中除最近的 2 个文件之外的所有文件

java - ubuntu 11.04 java 6 sun 字体

linux - 如何添加用户级环境变量以供 GUI linux 应用程序使用?

git - 在 Git 仓库中查找包含特定字符串模式的最后一次提交