Print data in file between pattern1 and pattern2 without printing pattern2

Viewed 75

So, I have some data that looks like this:

[SVP_VERSION_2]  
D:\CTD\01906932_2019_12_01\01906932_2019_12_01.svp  
Section 2019-335 10:55:14 18:53:56 -93:36:43  
0001.00 1539.85  
0002.00 1539.90  
0003.00 1539.83  
0004.00 1540.03  
Section 2019-335 10:55:14 18:53:56 -93:36:43  
0001.00 1540.05  
0002.00 1540.05  

I want to print the data from the first "Section" to the line before the 2nd "Section" Like so:

Section 2019-335 10:55:14 18:53:56 -93:36:43  
0001.00 1539.85  
0002.00 1539.90  
0003.00 1539.83  
0004.00 1540.03 

I know I can use:

sed -n '/Section/,/Section/p' file 

to get:

Section 2019-335 10:55:14 18:53:56 -93:36:43  
0001.00 1539.85  
0002.00 1539.90  
0003.00 1539.83  
0004.00 1540.03  
Section 2019-335 10:55:14 18:53:56 -93:36:43  

but I want to strip off the trailing "Section" line. I also know that I can pipe the output to a second sed to delete the last line, but I'm hoping to only make one call to sed. Is that possible?

2 Answers

This might work for you (GNU sed):

sed -n '/^Section/{:a;p;n;//q;ba}' file

Unset implicit printing -n and on matching a line beginning Section print that line and the following lines until another line matching the same pattern.

All lines before one beginning Section will be disregarded because the implicit printing has been switched off. Once a line beginning Section is matched the commands between { and } are executed.

Firstly a place holder :a is established. Then the current pattern space is printed p, the next line replaces the current pattern space by the introduction of n (it does not print line that is replaced because -n prevents this) and this line is checked to see if it matches the last regexp //q and if it does all processing is terminated (the q command ensures this). If it does not match the command ba sends the command flow back to the place holder :a.Thus all lines from the line beginning Section upto but not including the next line beginning Section are printed and then no further processing is done.

The alternative solution below achieves the same result but without using the -n switch, here the d command deletes any lines before one beginning Section and the Q command quits the processing without printing the current line (which would be the second occurrence of a line beginning Section).

Alternative:

sed '/^Section/{:a;n;//Q;ba};d' file

When you only have two lines with Section and GNU sed, you can use

sed -rz 's/.*(Section.*)Section.*/\1/' file
Related