Sunday, March 13, 2022

[SOLVED] print the block of text after the matched string

Issue

I am trying to print the block of the text between two @@@, to specify the block I am providing either foo_bar or hey_there as an identifier:

foo_bar
@@@
hey there
how are you
@@@

hey_there
@@@
Hello
howdy
@@@
    

I know simple /foo_bar/,/@@@/ construct is not going to help, as it will print till the 1st @@@, tried few other stuff but non helped.

awk '/foo_bar/{if($0 !~ /^@@@$/){print $0;getline}}'
foo_bar
awk '{if($0 ~ /foo_bar/){print $0};if($0 !~ /^@@@$/){print $0;getline}}'
foo_bar
foo_bar
hey there

Hello

Expected output(with or without @@@):

when foo_bar is provided print:

@@@
hey there
how are you
@@@

When hey_there is provided:

@@@
Hello
howdy
@@@

Solution

You may use:

awk -v RS= -v s='foo_bar' '$1 == s && match($0, /@@@.*@@@/) {
print substr($0, RSTART, RLENGTH)}' file

@@@
hey there
how are you
@@@

# and this one

awk -v RS= -v s='hey_there' '$1 == s && match($0, /@@@.*@@@/) {
print substr($0, RSTART, RLENGTH)}' file

@@@
Hello
howdy
@@@


Answered By - anubhava
Answer Checked By - Marie Seifert (WPSolving Admin)