2016-11-24 46 views
1

我有一個日誌文件,我需要的部分屬於特定類型的日誌。它可以是多行。
我不能在這裏直接發佈日誌文件,但它是以下格式:
從兩個相同模式之間的文件中提取內容

<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但使用「螺紋MESSAGE1」作爲如果有兩個連續的日誌和'MESSAGE1'鍵,則開始和結束模式都不起作用。
我想過使用Perl進行反向查找(工作),但不幸的是我不能使用Perl,'sed'和'awk'都不支持模式中的負向查找。
最近,我是用下面的「sed的」模式嘗試:

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中的輸出,但對於螺紋後」加入大括號 -/{H; d; X }'我在'命令'錯誤後得到'額外的字符'。 有更好的選擇嗎?或者有沒有一種方法可以在sed中使用大括號來分組命令?

回答

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 

如果不鍛鍊,那麼我建議您發佈更現實的樣本數據。

+0

非常感謝。我已驗證此命令適用於給定的文件。但我只有一個問題,現在kw ='線程-MESSAGE1'是一個常量字符串。它可以有正則表達式嗎? – akash12300

+1

如果你想傳入正則表達式,那麼在awk命令中使用'$ 2〜kw'而不是'$ 2 == kw' – anubhava