Print lines between two strings multiple occurencies (with sed, awk, or grep)

Hello,

I can extract lines in a file, between two strings but only one time.
If there are multiple occurencies, my command show only one block.

Example, monfichier.txt contains :

debut_sect
texte L1
texte L2
texte L3
texte L4
fin_sect

donnees inutiles 1
donnees inutiles 2

debut_sect
texte L5
texte L6
texte L7
texte L8
fin_sect

I want to extract blocks which are between debut_sect and fin_sect.
Result expected is :

texte L1
texte L2
texte L3
texte L4
texte L5
texte L6
texte L7
texte L8

I've tried : sed -e '1,/debut_sect/d' -e '/fin_sect/,$d' monfichier.txt

But it shows only last block :

texte L5
texte L6
texte L7
texte L8

Thanks

sed -n '/debut_sect/,/fin_sect/{/debut_sect\|fin_sect/d;p}' infile

--ahamed

Hi theclem35,

Using perl:

$ cat infile
debut_sect
texte L1
texte L2
texte L3
texte L4
fin_sect

donnees inutiles 1
donnees inutiles 2

debut_sect
texte L5
texte L6
texte L7
texte L8
fin_sect
$ perl -ne 'if ( $flip_flop = ( m/debut_sect/ .. m/fin_sect/ ) ) { print if $flip_flop !~ m/(?:1|E0)/ }' infile
texte L1
texte L2
texte L3
texte L4
texte L5
texte L6
texte L7
texte L8

Regards,
Birei.

Thanks a lot!
How can I add a string after each block ?
I tried sed -ne '/debut_sect/,/fin_sect/{/debut_sect\|fin_sect/d;p}' -ne '$a\\n---- END OF BLOCK ------\n' infile
But it add ---- END OF BLOCK ------ only one time, at the end of the file !

The more complicated you make it, the tougher it gets to do it in sed, which doesn't have things programmers want like variables and conditional statements. awk does, though.

awk '
# If we get a line containing fin_sect, and P is nonzero,
# print --- END OF BLOCK ---, and set P=0.
# We have this before the P statement, so that this runs
# first, preventing fin_sect itself from being printed.
P && /fin_sect/ { print "--- END OF BLOCK ---" ; P=0 }

# Print only when variable P set to nonzero value.
P
# If we get a line containing debut_sect, set P=1.
/debut_sect/ { P=1 }' infile
sed -n '/debut_sect/,/fin_sect/{s/fin_sect/--END OF BLOCK--/;/debut_sect/d;p}' infile

--ahamed

Thank you so much :slight_smile:

Hello,

I tried to use the examples from here to solve my case but without success. Could you help me. I have:

what I need is to extract the part:

I tried using

sed -n '/^RBE [0-9]/,/^ [0-9]/p'

but unfortunately without success. Any help will be highly appreciated. Thank you

TT0000013668528|ECBANYBANYB001|Jul2520121:00PM|MADHYAPRADESH|Bayan|IDEA|BHOPAL|9827936667|9302306262|9826470885TT0000013668528|ECBANYBANYB001|Jul2520121:00PM|MADHYAPRADESH|Bayan|AIRTEL|BHOPAL|9827936667|9302306262|9893124891
I have a input file as shown above.

Kindlu suggest me a query which will print repeated values once with non repeated values