Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awk or Sed: Return lines between two instances of the same pattern

I have a text file that looks like this:

-+- beginning text
hey there
hi there
ho there
-+- ending text
other stuff
that is
immaterial for
my purposes

I want to only grab the lines between the -+- patterns, so it will return:

hey there
hi there
ho there

The standard awk way:

awk '/beginning text/ {flag=1;next} /ending text/ {flag=0} flag {print}'

Works great as long as "beginning text" and "ending text" are different patterns.

Alas, for what I need, "Beginning text" and "Ending text" can change. The only consistent part of the two lines are the "-+-". All the rest of the text in the file can be completely different; I can't rely on any consistent patterns. The only reliable text is the -+-. And the awk fails when the two strings are identical.

Any ideas for how I can returns the lines between two discrete instances of the same pattern exclusive of the lines containing the patterns? Doesn't have to be awk, just something that will work in a bash shell script.

like image 968
Richard D Lawson Avatar asked Jul 15 '15 14:07

Richard D Lawson


2 Answers

If the pattern is the same and you don't want the pattern lines printed out then just combine the two patterns by inverting the flag each time you see the pattern.

awk '/^-\+-/ {flag=!flag; next} flag {print}'
like image 121
Etan Reisner Avatar answered Oct 08 '22 20:10

Etan Reisner


cat ttt
aaaa
bbbb
ccccc
bbbb
xxxxx
gggg
awk '/bbb/ {flag=1-flag; next} {if (flag) {print $0}}' ttt
ccccc
like image 26
stark Avatar answered Oct 08 '22 20:10

stark