Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select from fixed text pattern to 2nd blank line

Using sed/awk I want to select sections from a file that start with certain text until 2nd blank line. These patterns may occur multiple times in the file, all of which have to be extracted. For Example:

pattern1:
text1

text2

text3

pattern1:
text4

text5

text6

another text pattern1

more text

Desired result

pattern1:
text1

text2

pattern1:
text4

text5

I used a sed pattern

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sed -n '/^pattern/,/^$/p' filename

This only selects until first blank line.

The awk pattern I found also does not work

 awk '/^pattern/,/^$/&&++n==2' filename

>Solution :

Your Awk attempt is almost correct. Here’s a version that works, using the ~ operator combined with logical operators:

awk '$0~/^pattern/||n=0,$0~/^$/&&++n==2' filename

The regex pattern syntax /^$/ implicitly matches against $0 (the whole record) and doesn’t combine with other logical operators like &&, but if you make the regex match explicit with the ~ operator it works.

Also, the counter variable needs to be reset for each group.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading