Saving ranges using awk

Hi All,

Is there a way to save a range in variable for later printing?

for example write somthing like this:

awk '
/pattern1/,/pattern2/{f=range}
/pattern3/{print f}
'

I don't know excatly what "range" could be but is there a way to do this?

awk '
/pattern1/,/pattern2/{f?f=f RS $0:f=$0}
/pattern3/{print f}
' file

something like this?

a slight mod:

awk '
/pattern1/,/pattern2/{f?f=f RS $0:f=$0}
/pattern3/{print f;f=""}
' file
1 Like

to allow multiple range matches. Good idea :slight_smile:

Thanks alot for all your replies but when I tried the below one:

awk '
/pattern1/,/pattern2/{f?f=f RS $0:f=$0}
/pattern3/{print f;f=""}
' file

there was an error in the second line:

awk: syntax error near line 2
awk: illegal statement near line 2

Use nawk on Solaris.

Thanks It worked with nawk and gawk.

but the above code has one problem for example if pattern1 is character a, pattern2 is b and pattern3 is c, if the input data is in the folowing order:
a
d
b
a
e
c
b

the output would be the:
a
d
b
a
e
c
(since f is not reseted when a new range match is found), but I wanted to print only the last range found before finding pattern3, I needed the output to be like:
a
e
c
b

---------- Post updated at 02:03 AM ---------- Previous update was at 01:57 AM ----------

Another thing also, this won't work if pattern3 is in the range of pattern1 and pattern2 (like the above example) because printing will happen only in the range between pattern1 and pattern3, right?

and could the code be fixed to take care of such point?

Using patterns as a,b and c
Modify bold characters in below command as per your pattern1, pattern2 and pattern3.

awk '/a/,/b/{if(index($0,"a") > 0) f="";f?f=f RS $0;f=$0;if(index($0,"c") > 0) pr=1;if(index($0,"b") > 0 && pr==1 && f){print f;f="";pr=0;}next;}/c/{if(f){print f;f="";pr=0;}}' inputFile

For input:

a
d
b
a
e
c
b
a
e
r
t
c
b
u
t
a
g
h
b
c
e

Output is

a
e
c
b
a
e
r
t
c
b
a
g
h
b