Susanta Dutta
Susanta Dutta

Reputation: 447

How to grep line after pattern match only for one pattern out of many

I have a data file something like following. I want to grep "PANIC:", "Node 0/1/2/3:" and blank lines, but want to include next line ( "-A1" option ) only to one pattern - "PANIC:", not others. How to do that.

Kindly help to find solution

# cat data.txt
Node 0:
    DATE: 2020-12-19 04:06:44
    DATE: 2020-12-19 07:02:54
    PANIC: ABC
    DATE: 2020-12-19 20:02:54
    DATE: 2020-12-18 21:25:39

Node 1:
    DATE: 2020-12-20 09:35:43
    DATE: 2020-12-20 12:12:29

Node 2:
    

Node 3:
    DATE: 2020-12-19 20:03:00
    DATE: 2020-12-19 15:35:09
    PANIC: XYZ
    DATE: 2020-12-19 06:44:27
#
# cat data.txt | grep -A1 --no-group-separator -e PANIC: -e 'Node [0-7]:' -e ^$
Node 0:
    DATE: 2020-12-19 04:06:44
    PANIC: ABC
    DATE: 2020-12-19 20:02:54

Node 1:
    DATE: 2020-12-20 09:35:43

Node 2:
    DATE: 2020-12-20 03:00:15

Node 3:
    DATE: 2020-12-19 20:03:00
    PANIC: XYZ
    DATE: 2020-12-19 06:44:27
#

Expected filtered data is something like this

Node 0:
    PANIC: ABC
    DATE: 2020-12-19 20:02:54

Node 1:

Node 2:

Node 3:
    PANIC: XYZ
    DATE: 2020-12-19 06:44:27

Upvotes: 1

Views: 177

Answers (2)

William Pursell
William Pursell

Reputation: 212198

You can do as you ask with:

awk '/PANIC:/{print; getline; print} /Node [0-7]/ || /^ *$/' input

Although you don't mention it in the question, your sample output demonstrates that you also want to combine multiple blank lines in a single blank line. That can be done with:

awk '/./{a=0} /PANIC:/{print; getline; print} /^ *$/ && !a++{print} /Node [0-7]/' input

To print the line before the PANIC match, it's probably easiest to simply record the previous line. Something like:

 awk '/PANIC:/{print prev; print; getline; print} { prev = $0 } /Node [0-7]/ || /^ *$/' input | perl -00pe1

Upvotes: 1

stack0114106
stack0114106

Reputation: 8711

Using awk

awk  -F: ' /Node|PANIC/ { print; if($1~/PANIC/) { getline; print}  } ' data.txt

Results:

$ awk  -F: ' /Node|PANIC/ { print; if($1~/PANIC/) { getline; print}  } ' susanta.txt
Node 0:
    PANIC: ABC
    DATE: 2020-12-19 20:02:54
Node 1:
Node 2:
Node 3:
    PANIC: XYZ
    DATE: 2020-12-19 06:44:27
$

Upvotes: 1

Related Questions