regex - grep "Exception"但根据上一行过滤掉一个特定情况

标签 regex grep windows-subsystem-for-linux

在我的应用程序中,我修改了所有IP地址,以免干扰实际的生产系统。结果,我的应用程序抛出了很多异常。它们保存在名为filename的日志文件中。

我想过滤异常,但我不想看到由 IP 地址修改引起的异常。

这听起来很简单,因为这些异常前面有一行,其中包含无法连接

让我们看看如何做到这一点:

过滤异常:

grep "Exception" filename

还显示上一行:

grep -B 1 "Exception" filename

不显示包含“无法连接”的行:

grep -B 1 "Exception filename | grep -v "Failed to connect"

=> 不,这不是我想要的:这会过滤掉包含“无法连接”字样的行,但仍然显示实际的异常。我怎样才能不仅过滤掉异常呢?

我的文件名内容类似于:

... Failed to connect ...
... Exception ...
...
... (lots of these)
...
... <something else than "Failed to connect">
... Exception ...
...
... Failed to connect ...
... Exception ...
...
... (again lots of these)
...

我只对前面没有“无法连接”的行 ... Exception ... 感兴趣。

当我按 man grep 时,它以以下内容结尾:

GNU grep 3.4 ... 2019-12-29

有人有想法吗?
提前致谢

最佳答案

使用gnu-grep你可以做到这一点:

grep -zoP '(?m)^(?!.*Failed to connect).+\R.*Exception.*\R' file

... foo bar baz
... Exception ...

# where file content is
cat file

.. Failed to connect ...
... Exception ...
...
... (lots of these)
...
... foo bar baz
... Exception ...
...
... Failed to connect ...
... Exception ...
...
... (again lots of these)
...

RegEx Demo

命令详细信息:

  • -z:对整个文件进行操作,而不是一次一行
  • -o:仅返回匹配的文本
  • -P:启用 PCRE 模式
  • (?m):启用多行模式
  • ^:匹配行开头
  • (?!.*Failed to connect):当我们在一行中的任何位置出现 Failed to connect 时,使用负前瞻来断言失败
  • .+\R:匹配 1 个以上任意字符,后跟换行符
  • .*Exception.*\R:匹配 0 个以上任意字符,然后输入 Exception,然后再次匹配 0 个或多个任意字符,后跟换行符

关于regex - grep "Exception"但根据上一行过滤掉一个特定情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75384440/

相关文章:

linux - 了解 Grep 模式 - 示例

awk - Sed/awk : how to find and remove two lines if a pattern in the first line is being repeated; bash

git - 如何找到包含给定字符串的文件的树的提交 SHA1

linux - "apt-get install linux-headers-generic"安装在与 $(uname-r) 不同的目录中

ruby - ruby 中的正则表达式以获取字符串中的所有元音

php - 跨多个文件替换输入标签的值

regex - 在 sqlite3 中用 REGEXP 替换字符串的一部分

javascript - 在 RegEx 中创建第 n 级嵌套模式的算法

ssl - curl 请求 TLS 警报,Windows WSL 中的未知 CA

ubuntu - kubectl - 访问 GKE 集群时收到 PROTOCOL ERROR