从两个相同模式之间的文件中提取内容

时间:2016-11-24 11:10:05

标签: regex perl parsing awk sed

我有一个日志文件,我需要属于特定类型日志的部分。它可以是多行。
我不能直接在这里发布日志文件,但格式如下:

<date-format> Thread-MESSAGE1 random-message
line 1
line 2
line 3
line 4
<date-format> Thread-MESSAGE1 random-message2
line 5
<date-format> Thread-MESSAGE2 random-message3
line 6
line 7
line 8
line 9
<date-format> Thread-MESSAGE3 random-message4
<date-format> Thread-MESSAGE1 random-message5
<date-format> Thread-MESSAGE1 random-message6
line 10
line 11
<date-format> Thread-MESSAGE7 random-message7
<date-format> Thread-MESSAGE8 random-message9
<date-format> Thread-MESSAGE9 random-message10
<date-format> Thread-MESSAGE1 random-message11 

我需要输出:

<date-format> Thread-MESSAGE1 random-message
line 1
line 2
line 3
line 4
<date-format> Thread-MESSAGE1 random-message2
line 5
<date-format> Thread-MESSAGE1 random-message5
<date-format> Thread-MESSAGE1 random-message6
line 10
line 11
<date-format> Thread-MESSAGE1 random-message11 

我尝试使用sed但使用&#39;线程MESSAGE1&#39;因为如果有两个连续的日志,那么开始和结束模式都不起作用。&#39; MESSAGE1&#39;键。
我想过使用Perl(使用Perl)使用否定查找,但遗憾的是我不能使用Perl,也不能使用Perl&#39;也不是&#39; awk&#39;支持模式中的负向查找。
最近我尝试了以下&#39; sed&#39;模式:

tac source_file.log | sed -n '{/<date-format> Thread-/!H; /<date-format> Thread-/{H;d;x} /<date-format> Thread-MESSAGE1/p; d;}' > test.log

之后的想法是反转test.log的输出,但是在&#39; Thread - / {H; d; x}&#39;之后添加花括号。我在命令后得到额外的字符&#39;错误。 还有更好的选择吗?或者有没有办法在sed中使用花括号对命令进行分组?

1 个答案:

答案 0 :(得分:2)

您可以使用此awk命令:

awk -v kw='Thread-MESSAGE1' '$2 ~ /^Thread-/ {p = ($2 == kw)} p' file

<date-format> Thread-MESSAGE1 random-message
line 1
line 2
line 3
line 4
<date-format> Thread-MESSAGE1 random-message2
line 5
<date-format> Thread-MESSAGE1 random-message5
<date-format> Thread-MESSAGE1 random-message6
line 10
line 11
<date-format> Thread-MESSAGE1 random-message11

如果没有锻炼,那么我建议您发布更实际的样本数据。

相关问题