nTOXIC
nTOXIC

Reputation: 143

How to extract lines between two patterns using lines in between as a printing condition

I'm searching for a way to use the following code as a basis

function get { 
  awk '/^\[ '"$1"' \]/{p=1;next} /^$/{p=0} p' "${MY_FILE_PATH}"
}

to extract a complete section of myfile:

[ SECTION_1 ]
info 1
info 2
info 3

[ SECTION_2 ]
info 4
info 5
info 6

conditioned on the entries it has.

When I'm asking for info 2 for example, it should print the complete SECTION_1. I thought of using additional flags, but I did not get the desired results.

Is there any solution that can be derived from the function get above to achieve this behavior?

Thanks for tipps and hints :)

Upvotes: 1

Views: 51

Answers (1)

anubhava
anubhava

Reputation: 784998

You can this awk with RS=:

awk -v s="SECTION_1" -v RS= '$0 ~ "\\[ " s " \\]"' file
[ SECTION_1 ]
info 1
info 2
info 3

Or using info 2 as search string:

awk -v s="info 2" -v RS= '$0 ~ s' file
[ SECTION_1 ]
info 1
info 2
info 3

Upvotes: 2

Related Questions