Delete lines between two patterns excluding the other lines containing these pattern

I would want to only remove the lines between PATTERN1(aaa) and PATTERN2(ccc), excluding the others lines where the patterns matches.

I trying to delete the empty line between PATTERN1(aaa) and PATTERN2(ccc), line 8 in my example...This line will be no all times in same location, that is the reason, why I try to remove it using the 2 patterns.

Essentially it boils down to: "If a blank line is found between aaa and ccc then remove it..

input file

aaa 409
bbb 201

122 0.98
aaa 1.47
aaa 0.00
aaa 0.00

ccc 0.00
121 0.01
135 1.99

output file

aaa 409
bbb 201

122 0.98
aaa 1.47
aaa 0.00
aaa 0.00
ccc 0.00
121 0.01
135 1.99
attempts
sed  '/aaa/,/ccc/{//p;d;}' file
sed '/aaa/,/ccc/{//!d}' file
awk '/aaa/{g=1;next}/ccc/{g=0;next}g' file

Thanks in advance

Not that easy as your start pattern occurs multiple times. For your sample, adapting your first attempt:

tac file | sed  '/ccc/,/aaa/{/^ *$/d;}' | tac
aaa 409
bbb 201

122 0.98
aaa 1.47
aaa 0.00
aaa 0.00
ccc 0.00
121 0.01
135 1.99

Are multiple end patterns ("ccc") possible?

EDIT: or

sed -zr 's/(aaa[^\n]*)\n\n([^\n]*ccc)/\1\n\2/' file
aaa 409
bbb 201

122 0.98
aaa 1.47
aaa 0.00
aaa 0.00
ccc 0.00
121 0.01
135 1.99
1 Like

Hi
GNU extension includes a multiline modifier M,m

sed -rz 's/(a.*\n)\n+(c.*)/\1\2/m'

--- Post updated at 06:36 ---

the wolves be sated and the sheep intact

sed -r ':1;N;/\n$/b1;s/(^a.*$)\n+(^c.*$)/\1\n\2/m'

the last example is not true and needs to be fixed

1 Like

Dear RudiC and nezabudka
Thanks a lot for the codes.

I am glad if it was useful, @jiam912
The code has grown a bit, but I could not find another way to get around the buffer size limit

sed -r ':1;N;/a[^\n]*\n*$/b1;l;s/(^a.*$)\n+(^c.*$)/\1\n\2/m'

The problem was as follows.
If the string starting with 'a' was even line then the code did not work properly.
Add the 'l' command to look at the contents of the buffer (the line marked at the end with a dollar sign)
and add one line to the input file.

cat file
aaa 409
bbb 201

122 0.98
aaa 1.47
aaa 0.00
aaa 0.00
aaa 1.47

ccc 0.00
121 0.01
135 1.99
sed -r ':1;N;/\n$/b1;l;s/(^a.*$)\n+(^c.*$)/\1\n\2/m' file
aaa 409\nbbb 201$
aaa 409 
bbb 201 
\n122 0.98$

122 0.98
aaa 1.47\naaa 0.00$
aaa 1.47
aaa 0.00
aaa 0.00\naaa 1.47$
aaa 0.00
aaa 1.47
\nccc 0.00$

ccc 0.00
121 0.01\n135 1.99$
121 0.01
135 1.99

а new version

sed -r ':1;N;/a[^\n]*\n*$/b1;l;s/(^a.*$)\n+(^c.*$)/\1\n\2/m' file
aaa 409\nbbb 201$
aaa 409 
bbb 201 
\n122 0.98$

122 0.98
aaa 1.47\naaa 0.00\naaa 0.00\naaa 1.47\n\nccc 0.00$
aaa 1.47
aaa 0.00
aaa 0.00
aaa 1.47
ccc 0.00
121 0.01\n135 1.99$
121 0.01
135 1.99