This might work for you (GNU sed):
echo -e "a\nyyyy\nxxxx\nzzzz\nb" | sed 'N;/^xxxx/M{/^xxxx/d;$!N;d};P;D'
a
b
This keeps a window of two lines in the pattern space and if the required regexp is found in either the first or second line, reads the following line and then deletes all three lines. The edge cases are if the regexp is found in either the first or last lines when there is no line before/afterward. In these cases only two lines can be deleted.
Incidentally this solution may have unearthed a possible bug in GNU sed. The M
flag of an address allows the ^
and $
metacharacters to be used as zero length markers in a regexp for the start and end of line in multiline strings. The empty address //
reuses a previously stated address. Should that address be one that includes a multiline flag? Presently it appears to include the flag even if it is not stated i.e.
sed 'N;/^xxxx/M{/^xxxx/d;$!N;d};P;D' file
produces a different (correct) result to:
sed 'N;/^xxxx/M{//d;$!N;d};P;D' file
if xxxx
appears on the second line of a file.