DomainsFeatured
DomainsFeatured

Reputation: 1506

Print paragraph after matching pattern

I would like to print the lines between two empty lines only after a match is made. My data looks like this:

List A
Item 1
Item 2
Item 3

Item 4
Item 5

List B
Item 1
Item 2
Item 3

Thus, I'm trying to get a sed or awk or grep command to match List A and get the output of

Item 4
Item 5

So far, I have tried doing:

sed '/^$/,/^$/!d'

and

sed '/list\sA.*^$/,/^$/!d'

In this case, I'm trying to print the range and define the first pattern as the string and everything included until the empty line.

I have also tried other code with:

awk -v RS='' -v ORS='\n\n'

But, this only gives me the paragraph that contains the pattern, I'm trying to get the paragraph after that.

Finally, I think it is something using sed -n and uses the { } with labels but I'm just not advanced enough to put it all together. Would really appreciate if you could point me in the right direction.

Upvotes: 1

Views: 1324

Answers (2)

hek2mgl
hek2mgl

Reputation: 158080

I would suggest to use awk here as shown in fedorqui's answer. However, the following sed command would work as well:

sed -n '/List A/{:a;n;/^$/!ba;:b;n;/^$/!{p;bb}}' file

Explanation:

/List A/ { 
    :a          # Label "a"
    n           # Get new line from input
    /^$/! ba    # If this line is not empty jump back to :a
    :b          # Label "b"
    n           # Get new line from input
    /^$/! {     # If this line is not empty:
        p       #   Print the line
        bb      #   Jump back to :b  
    }
}

The option -n suppresses printing of lines unless p is used.

Upvotes: 0

fedorqui
fedorqui

Reputation: 289995

When you match a pattern, get the next record with getline:

$ awk -v RS='' '/List A/ {getline; print}' file
Item 4
Item 5

Upvotes: 4

Related Questions