cancel
Showing results for 
Search instead for 
Did you mean: 

Search between two lines

SOLVED
Go to solution
lawrenzo_1
Super Advisor

Search between two lines

Hi All,

I have a large file and want to display the data between two lines but not the lines searched ie:


data1
data2
data3
info required
info required
info required
data44
data45

etc

data3 and data44 will always be constant so using awk I can:

awk '/^data3/,/^data44/ {print $0}' file

data3
info required
info required
info required
data44

how can I ommit data3 and data44?

Thanks

Chris.
hello
7 REPLIES
Mel Burslan
Honored Contributor
Solution

Re: Search between two lines



awk '/^data3/,/^data44/ {print $0}' file|sed -e "1,1d"| sed -e "\$,\$d"

will the above work for you ??
________________________________
UNIX because I majored in cryptology...
Laurent Menase
Honored Contributor

Re: Search between two lines

awk 'BEGIN {s=0}/^data3/{s=1; continue}/^data44/ {s=2; continue} (s==1){print $0}' file


James R. Ferguson
Acclaimed Contributor

Re: Search between two lines

Hi Chris:

Similar to Laurent's:

# perl -ne '$x++,next if /data3/;$x-- if /data44/;print if $x' file

Regards!

...JRF...

Laurent Menase
Honored Contributor

Re: Search between two lines

even better, since it exit when reaching data44
awk 'BEGIN {s=0}/^data3/{s=1; continue}/^data44/ {s=2; break} (s==1){print $0}' file
lawrenzo_1
Super Advisor

Re: Search between two lines

thanks all - good managable code

Chris
hello
Dennis Handly
Acclaimed Contributor

Re: Search between two lines

>Laurent: even better, since it exit when reaching data44

I would have never thought to use continue/break since these are only used in C to break/continue out of loops or case. Not separate patterns. I don't think your break really does anything.

Instead I would use next and exit:
awk '
BEGIN {s=0}
/^data3/ {s=1; next}
/^data44/ {exit}
s {print $0}'

Of course your solution will find multiple ranges of data3/data44 pairs.
Laurent Menase
Honored Contributor

Re: Search between two lines

in fact you are right
continue/break just does the same
as a next in that context.
I made that error for years, thanks.