我正在尝试编写日志解析脚本来提取失败的事件。我可以用grep来提取这些:

$ grep -A5 "FAILED" log.txt

2008-08-19 17:50:07 [7052] [14] DEBUG:      data: 3a 46 41 49 4c 45 44 20 20 65 72 72 3a 30 32 33   :FAILED  err:023
2008-08-19 17:50:07 [7052] [14] DEBUG:      data: 20 74 65 78 74 3a 20 00                            text: .
2008-08-19 17:50:07 [7052] [14] DEBUG:    Octet string dump ends.
2008-08-19 17:50:07 [7052] [14] DEBUG: SMPP PDU dump ends.
2008-08-19 17:50:07 [7052] [14] DEBUG: SMPP[test] handle_pdu, got DLR
2008-08-19 17:50:07 [7052] [14] DEBUG: DLR[internal]: Looking for DLR smsc=test, ts=1158667543, dst=447872123456, type=2
--
2008-08-19 17:50:07 [7052] [8] DEBUG:      data: 3a 46 41 49 4c 45 44 20 20 65 72 72 3a 30 32 34   :FAILED  err:024
2008-08-19 17:50:07 [7052] [8] DEBUG:      data: 20 74 65 78 74 3a 20 00                            text: .
2008-08-19 17:50:07 [7052] [8] DEBUG:    Octet string dump ends.
2008-08-19 17:50:07 [7052] [8] DEBUG: SMPP PDU dump ends.
2008-08-19 17:50:07 [7052] [8] DEBUG: SMPP[test] handle_pdu, got DLR
2008-08-19 17:50:07 [7052] [8] DEBUG: DLR[internal]: Looking for DLR smsc=test, ts=1040097716, dst=447872987654, type=2

我感兴趣的是,对于每个块,错误代码(即第一行上的“FAILED err:023”的“023”部分)和dst数字(即“447872123456”)。来自最后一行的“dst = 447872123456”。)

任何人都可以帮助shell one-liner来提取这两个值,或者提供一些关于我应该如何处理它的提示吗?

有帮助吗?

解决方案

grep -A 5 FAILED log.txt | \              # Get FAILED and dst and other lines
    egrep '(FAILED|dst=)' | \             # Just the FAILED/dst lines
    egrep -o "err:[0-9]*|dst=[0-9]*" | \  # Just the err: and dst= phrases
    cut -d':' -f 2 | \                    # Strip "err:" from err: lines
    cut -d '=' -f 2 | \                   # Strip "dst=" from dst= lines
    xargs -n 2                            # Combine pairs of numbers

023 447872123456
024 447872987654

与所有shell“one”-liners一样,几乎可以肯定有更优雅的方式来做到这一点。但是,我发现迭代方法非常成功,可以获得我想要的东西:从太多的信息开始(你的grep),然后缩小我想要的行(用grep),然后剪掉我想要的每一行的部分(用切)。

虽然使用linux工具箱需要更多行,但您只需了解一些命令的基础知识即可完成您想要的任何操作。另一种方法是使用awk,python或其他脚本语言,这些语言需要更专业的编程知识,但占用的屏幕空间更少。

其他提示

Ruby中的一个简单解决方案,这里是 filter.rb

#! /usr/bin/env ruby
File.read(ARGV.first).scan(/:FAILED\s+err:(\d+).*?, dst=(\d+),/m).each do |err, dst|
  puts "#{err} #{dst}"
end

使用以下命令运行:

ruby filter.rb my_log_file.txt

你得到:

023 447872123456
024 447872987654

如果总是有相同数量的字段

grep -A5 "FAILED" log.txt | awk '$24~/err/ {print $24} $12~/dst/{print $12}' error.txt

err:023
dst=447872123456,
err:024
dst=447872987654,

根据文件其余部分的外观,您可以跳过grep all togther。

$ 24~ / err / {print $ 24} " part告诉awk打印字段号24如果它包含错误,〜/ XXX /其中XXX是正则表达式。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top