With sed
:
sed -n ' N /\n.*pattern/ P D'
Normally the pattern space in sed
contains a single line, the current line of input. It's like a one-line window that moves through the input as lines come.
Here we start each cycle by trying to append the next line of input to the pattern space (N
). We end each cycle by deleting the initial line of the pattern space (D
). This way the pattern space is a two-line window that moves through the input as lines come.
Having the two-line window, we can easily detect when pattern
is in the second line of the pattern space (/\n.*pattern/
, where \n
matches a newline character) and only then print the first line of the pattern space (P
).
Details here: POSIX specification of sed
.