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
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.