对字符串的实例进行计数,不包括时间戳相隔 <1 分钟的情况



我是编码的初学者。我有一个脚本,可以在文件中为特定的单词进行grep。我需要它的出现次数,但我要找的词是,级联。因此,如果在不到1分钟的时间内再次重复,我想忽略发生的情况。但如果发生的设备与第一次发生的设备不同,则不应忽略
例如:file1.txt

file .txt    2018.09.06 21:27:45.001 There is a error 12345
file .txt    2018.09.06 21:27:45.009 error 12345 is reported on device-1
file .txt    2018.09.06 21:27:45.500 There is a error 12345
file .txt    2018.09.06 21:27:45.601 error 12345 is reported on device-1
file .txt    2018.09.06 21:27:46.899 There is a error 12345
file .txt    2018.09.06 21:27:46.905 error 12345 is reported on device-1
file .txt    2018.09.06 21:27:49.203 There is a error 12345
file .txt    2018.09.06 21:27:49.491 error 12345 is reported on device-6
file .txt    2018.09.06 21:27:52.703 There is a error 12345
file .txt    2018.09.06 21:29:52.991 error 12345 is reported on device-6

结果是

grep -c 12345 file1.txt
10

我得到的结果=10

我需要的结果=3

如何忽略基于时间戳的重复出现。

你有多在乎"彼此在1分钟内"的部分?如果说"在一分钟内忽略多个事件"就足够了,那么这就相当简单了。

首先获取所有"错误xyz已报告"行的列表

$ grep "error 12345 is reported" tfile.txt
file .txt    2018.09.06 21:27:45.009 error 12345 is reported on device-1
file .txt    2018.09.06 21:27:45.601 error 12345 is reported on device-1
file .txt    2018.09.06 21:27:46.905 error 12345 is reported on device-1
file .txt    2018.09.06 21:27:49.491 error 12345 is reported on device-6
file .txt    2018.09.06 21:29:52.991 error 12345 is reported on device-6

然后使用sed将这些减少为HH:MM device-number格式

$ grep reported tfile.txt | sed 's/.*(..:..):.*reported on (.*)/1 2/'
21:27 device-1
21:27 device-1
21:27 device-1
21:27 device-6
21:29 device-6

然后找到唯一的条目

$ grep reported tfile.txt | sed 's/.*(..:..):.*reported on (.*)/1 2/' | uniq
21:27 device-1
21:27 device-6
21:29 device-6

最后计算

$ grep reported tfile.txt | sed 's/.*(..:..):.*reported on (.*)/1 2/' | uniq | wc -l
3

您需要解析出时间戳,进行一些日期-时间计算(总是有点困难,但至少您可能没有跨越时区,尽管您可能会周期性地跨越夏令时,我认为您没有足够的信息来判断何时会发生这种情况(。这可能意味着一个简单的grep是不够的,您需要读取bash中的每一行,解析并跟踪它

然后,您将需要类似sed或awk的东西来解析该行。只要你无论如何都这么做,你可能只想在整个过程中使用awk。我从未使用过awk进行时间戳管理,尽管我看到了它的手册页,所以它应该能够处理它。剩下的就是根据时间戳跟踪设备名称,awk处理得很好。

然而,我建议为此采用更高层次的语言。无论是perl、python还是ruby,它们都应该能够相当轻松地处理这一问题。

相关内容

最新更新