gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:22:01 25 4
gpt4 key购买 nike

我有一个具有格式的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com