我在Linux机器上有大量的java日志,我正在尝试找到一个grep表达式或其他东西(perl,awk),它在我身体的某个地方给我一个匹配的整个日志条目。 Logstash看起来可以完成这项工作,但是带有板载工具的东西会更好。
一个例子应该是最好的。这是一个包含5个不同条目的示例日志:
25 Aug 2016 14:00:46,435 DEBUG [User][IP][rsc] An error occurred
java.Exception: Foo1
at xyz
25 Aug 2016 14:00:46,436 Foo2 [User][IP][rsc] Some error occured
25 Aug 2016 14:00:46,436 DEBUG [User][IP][rsc] Somethin occured Foo3
25 Aug 2016 14:18:18,224 XYZ [User][IP][rsc] Some problems
More: bla1
More: bla2
USER.bla.bla: Blala::123 - 456
More: Could not open something
at 567
at 890
Caused by: Foo4: Could not open another thing
at 123
at 456
... 127 more
Caused by: gaga
at a1a2a3
at b3b3b3
... 146 more
25 Aug 2016 14:18:20,118 SSO [User][IP][rsc] Process: error -
Could not Foo5
<here is a blank line>
当我搜索“Foo1”时,我需要:
25 Aug 2016 14:00:46,435 DEBUG [User][IP][rsc] An error occurred
java.Exception: Foo1
at xyz
当我搜索“Foo2”时:
25 Aug 2016 14:00:46,436 Foo2 [User][IP][rsc] Some error occured
对于“Foo3”:
25 Aug 2016 14:00:46,436 DEBUG [User][IP][rsc] Somethin occured Foo3
对于“Foo4”:
25 Aug 2016 01:18:18,224 XYZ [User][IP][rsc] Some problems
More: bla1
More: bla2
USER.bla.bla: Blala::123 - 456
More: Could not open connection
at 567
at 890
Caused by: Foo4: Could not open connection
at 123
at 456
... 127 more
Caused by: gaga
at a1a2a3
at b3b3b3
... 146 more
最后为“Foo5”:
25 Aug 2016 01:18:20,118 SSO [User][IP][rsc] Process: error -
Could not Foo5
当我搜索“Foo”时,应返回所有内容。 这样的事情可能吗?也许甚至作为一个班轮? 我想在Webmin Custom Commands模块中使用它,我通过变量提供表达式。
我目前唯一的基本想法是搜索表达式并使用“[”作为模式来识别新条目的开始位置。
提前感谢任何有想法的人!
答案 0 :(得分:1)
一个sed解决方案 - 适用于不允许使用awk的环境 - 相同的sed命令显示在oneliner和multiline表单上
pat=$1
# oneliner form
#sed -nr '/^[0-9]{2} [a-zA-Z]{3} [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3} /!{H; $!b}; x; /'"$pat"'/p; ${g; /^[0-9]{2} [a-zA-Z]{3} [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3} /!q; /'"$pat"'/p }'
# multiline form
sed -nr '
/^[0-9]{2} [a-zA-Z]{3} [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3} /!{H; $!b}
x
/'"$pat"'/p
${
g
/^[0-9]{2} [a-zA-Z]{3} [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3} /!q
/'"$pat"'/p
}'
在行首开始使用时间戳作为记录开始 - 累积非时间戳行,即保留空间中的记录主体 - 交换保留空间和记录开始时的模式空间 - 如果模式匹配则打印记录
最后一行记录开始的特例 - 必须从保留空间重新获取并单独测试模式匹配
使用pat
bash变量
答案 1 :(得分:0)
我将awk RS设置为多行记录的时间戳模式:
pat=$1
awk -vpat="$pat" '
BEGIN{
RS="[0-9]{2} [a-zA-Z]{3} [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3} "
}
$0 ~ pat {printf("%s%s", prt, $0)}
{prt=RT}
'