简体   繁体   中英

BASH grep with multiple parameters + n lines after one of the matches

I have a bunch of text as a output from command, I need to display only specific matching lines plus some additional lines after match "message" (message text is obviously longer than 1 line)

what I tried was:

grep -e 'Subject:' -e 'Date:' -A50 -e 'Message:'

but it included 50 lines after EACH match, and I need to pass that only to single parameter. How would I do that?

code with output command:

(<...> | telnet <mailserver> 110 | grep -e 'Subject:' -e 'Date:' -A50 -e 'Message:'

Part of the telnet output:

Date: Tue, 10 Sep 2013 16 
Message-ID: <00fb01ceae25$ 
MIME-Version: 1.0 
Content-Type: multipart/alternative;
    boundary="----=_NextPart_000_00FC_01CEAE3E.DE32CE40"
X-Mailer: Microsoft Office Outlook 12.0
Thread-Index: Ac6uJWYdA3lUzs1cT8....
Content-Language: lt
X-Mailman-Approved-At: Tue, 10 Sep 2013 16:0 ....
Subject: ...
X-BeenThere: ...
Precedence: list

Try following:

... | telnet ... > <file>
grep -e 'Subject:' -e 'Date:' <file> && grep -A50 -e 'Message:' <file>

Will need to dump the output to a file first.

This can be done with awk as well, without the need for dumping output to a file.

... | telnet ... | awk '/Date:/ {print}; /Subject:/ {print}; /Message:/ {c=50} c && c--'

With grep it would be hard to do. Better use awk for this

awk '/Subject:|Date:/;/Message:/ {while(l<=50){print $0;l++;getline}}'

Here the awk prints 50 lines below the Message: pattern and only one line is printed for all other patterns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM