2

This question is similar to How to show lines after each grep match until other specific match? thus answers may be similar to those there.

I am trying to grab and extract from a file the lines that are after the lines that are matching a TARGET value ("forms=2", in my case) and the next empty line. The segment of my file is like below:

forms=1
Code=00416T0
Code=00416T0

forms=2       #Target**
Code=06538T0  #grab this line
Code=06538T0  #grab this line
Code=11288T0  #grab this line
Code=11288T0  #grab this line

forms=1
Code=00549T0
Code=00549T0
Code=00549T0

forms=2      #Target**
Code=00553T0 #grab this line
Code=02576T0 #grab this line
Code=02576T0 #grab this line

forms=1
Code=11099T0 

So I would like to find a way according to Target "forms=2" to have the following lines even if same of those grabbing lines are identical

Code=06538T0 #grab this line
Code=06538T0 #grab this line
Code=11288T0 #grab this line
Code=11288T0 #grab this line
Code=00553T0 #grab this line
Code=02576T0 #grab this line
Code=02576T0 #grab this line

Any help please?

Hauke Laging
  • 90,279

3 Answers3

2

The following might work for you:

sed -n '/forms=2/,/^[^C]/{/^[^C]/b;p}' filename

or, as suggested by Graeme:

sed -n '/^forms=2/,/^[^C]/ {/^Code=/p}' filename

For your input, it'd produce:

Code=06538T0  #grab this line
Code=06538T0  #grab this line
Code=11288T0  #grab this line
Code=11288T0  #grab this line
Code=00553T0 #grab this line
Code=02576T0 #grab this line
Code=02576T0 #grab this line

For handling cases where you might lines like form=20, you could say:

sed -n '/^forms=2\b/,/^[^C]/ {/^Code=/p}' filename    
devnull
  • 10,691
1

Using perl:

%perl -lne 'if(/forms=2/.../^$/ and $_!~/forms=2|^$/){print}' file
Code=06538T0  #grab this line
Code=06538T0  #grab this line
Code=11288T0  #grab this line
Code=11288T0  #grab this line
Code=00553T0 #grab this line
Code=02576T0 #grab this line
Code=02576T0 #grab this line

Using awk:

awk '/forms=2/,/^$/{if(!/forms=2/&&!/^$/)print}' file

or:

awk '/^$/{flag=0};flag;/forms=2/{flag=1}' file

Using sed (GNU sed):

sed '/forms=2/,/^$/{//!b};d'
cuonglm
  • 153,898
0

Another sed:

sed -n '/forms=2 /,/^$/ {/^.*forms.*$/d; /^$/d; s/  *#grab/ #grab/}' input

.

Code=06538T0 #grab this line
Code=06538T0 #grab this line
Code=11288T0 #grab this line
Code=11288T0 #grab this line
Code=00553T0 #grab this line
Code=02576T0 #grab this line
Code=02576T0 #grab this line