logging - 如何在连续行中找到相同的字符串,然后打印连续包含它们的所有行

标签 logging awk

我有一个具有格式的 ping 日志文件

2021/02/15 14:22:27 : Reply[1] from 10.10.10.1: bytes=32 time=31.9 ms TTL=244 jitter=0.00 ms
2021/02/15 14:22:27 : Reply[2] from 10.10.10.1: bytes=32 time=32.5 ms TTL=244 jitter=0.03 ms
2021/02/15 14:22:28 : 10.10.10.1: request timed out
2021/02/15 14:22:28 : Reply[4] from 10.10.10.1: bytes=32 time=29.9 ms TTL=244 jitter=0.28 ms
2021/02/15 14:22:29 : Reply[5] from 10.10.10.1: bytes=32 time=27.4 ms TTL=244 jitter=0.42 ms
2021/02/15 14:22:29 : Reply[6] from 10.10.10.1: bytes=32 time=31.3 ms TTL=244 jitter=0.63 ms
2021/02/15 14:22:30 : 10.10.10.1: request timed out
2021/02/15 14:22:31 : 10.10.10.1: request timed out
2021/02/15 14:22:31 : 10.10.10.1: request timed out
2021/02/15 14:22:32 : Reply[10] from 10.10.10.1: bytes=32 time=33.8 ms TTL=244 jitter=0.91 ms

我只寻找没有回复两次或多次的行(一次只有一次超时就可以了)。

我尝试过像这样使用 awk,但问题是它会打印与我想要的内容匹配的每一行,除了最后一行......

awk -F " : " "($2 !~ /Reply/ && $2 == prev2) {print prevline} {prev2 = $2; prevline = $0} <file>

我的问题是如何修改 awk 命令来打印连续匹配条件的最后一行?或者也许是 python 解决方案?或者有正则表达式的东西?

所以预期的输出是

2021/02/15 14:22:30 : 10.10.10.1: request timed out
2021/02/15 14:22:31 : 10.10.10.1: request timed out
2021/02/15 14:22:31 : 10.10.10.1: request timed out

因为它发生在 2 个或更多连续行上,但是我的 awk 只打印出前两行而不是最后一行(它不会打印从 14:22:28 开始的超时,因为它只发生一次,但是预计!)

最佳答案

根据您显示的示例,您可以尝试以下操作吗?

awk '
!/request timed out/{
  if(count>=2){ print val }
  val=""
  count=0
}
/request timed out/{
  count++
  val=(val?val ORS:"")$0
}
END{
  if(count>=2){ print val }
}
'  Input_file

说明:为上述内容添加详细说明。

awk '                           ##Starting awk program from here.
!/request timed out/{           ##Checking condition if line is NOT having request timed out then do following.
  if(count>=2){ print val }     ##Checking condition if count is greater than equal to 2 then print val here.
  val=""                        ##Nullify val here.
  count=0                       ##Setting count to 0 here.
}
/request timed out/{            ##Checking condition if request timed out found in line then do following.
  count++                       ##Increasing count value with 1 here.
  val=(val?val ORS:"")$0        ##Adding line into val and keep concatenating its value to it.
}
END{                            ##Starting END block of this code here.
  if(count>=2){ print val }     ##Checking condition if count is greater than equal to 2 then print val here.
}
'  Input_file                   ##mentioning Input_file name here.

关于logging - 如何在连续行中找到相同的字符串,然后打印连续包含它们的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66280447/

相关文章:

oracle - 在 sqlplus 中执行时将 plsql 错误消息重定向到日志文件

记录经验法则

arrays - awk 查找数组的最小值和最大值

bash - 如何过滤我的组/集群以仅保留具有不同 column2 值的组/集群?

bash - 使用 sed/awk 在启动时写入/etc/networking/interfaces?

logging - 依赖注入(inject)和日志接口(interface)

logging - 在 grails-app 之外的 Grails 类中注入(inject)日志对象

linux - shell脚本过滤du并通过子文件夹中文件内的字符串查找

awk:警告:转义序列 `\]'被视为纯 `]'

php - 管理大型日志文件