Grep for string if contained in several consecutive lines

时间:2018-04-18 18:07:53

标签: grep

I have a logfile in which I want to find lines that contain a specific string, if it's at least five consecutive lines that contain it.

E.g. my logfile looks like this:

Sent RTP packet to      10.124.193.26:12486 (type 09, seq 030081, ts 2726949472, len 000160)
Got  RTP packet from    10.124.193.26:12486 (type 09, seq 052435, ts 174852800, len 000160)
Sent RTP packet to      10.124.193.26:12486 (type 09, seq 030082, ts 2726949632, len 000160)
Got  RTP packet from    10.124.193.26:12486 (type 09, seq 052436, ts 174852960, len 000160)
Sent RTP packet to      10.124.193.26:12486 (type 09, seq 030083, ts 2726949792, len 000160)
Got  RTP packet from    10.124.193.26:12486 (type 09, seq 052437, ts 174853120, len 000160)
Sent RTP packet to      10.124.193.26:12486 (type 09, seq 030084, ts 2726949952, len 000160)
Got  RTP packet from    10.124.193.26:12486 (type 09, seq 052438, ts 174853280, len 000160)
Sent RTP packet to      10.124.193.90:11836 (type 09, seq 055416, ts 87947536, len 000160)
Sent RTP packet to      10.124.193.90:11836 (type 09, seq 055417, ts 87947696, len 000160)
Sent RTP packet to      10.124.193.90:11836 (type 09, seq 055418, ts 87947856, len 000160)
Sent RTP packet to      10.124.193.90:11836 (type 09, seq 055419, ts 87948016, len 000160)
Sent RTP packet to      10.124.193.90:11836 (type 09, seq 055420, ts 87948176, len 000160)
Sent RTP packet to      10.124.193.90:11836 (type 09, seq 055421, ts 87948336, len 000160)
Sent RTP packet to      10.124.193.90:11836 (type 09, seq 055422, ts 87948496, len 000160)
Sent RTP packet to      10.124.193.90:11836 (type 09, seq 055423, ts 87948656, len 000160)
Sent RTP packet to      10.124.193.90:11836 (type 09, seq 055424, ts 87948816, len 000160)
Sent RTP packet to      10.124.193.90:11836 (type 09, seq 055425, ts 87948976, len 000160)

The first lines begin with either "Sent" or "Got" alternating. Those are fine and I am not interested in them. Then it's consecutive lines starting with "Sent" only. Those I want to find. How can I use grep or another command to find them?

1 个答案:

答案 0 :(得分:0)

您可以使用以下命令:

$ cat <filename> | awk '{ if( pre == "Sent" && $1 == "Sent" ) {print $0} ; {pre=$1} }'

说明:

记住最后一行的第一个单词。如果是&#34;已发送&#34;,如果当前行的第一个字也是&#34;已发送&#34;,则打印当前行。