Hier ist , wie zu emulieren grep -B1mit sed:
sed '$!N;/pattern/P;D' infile
Es ist sehr ähnlich den man hier . Genau wie beim anderen wird die Next-Zeile Peingelesen , diesmal jedoch bis zur ersten \newline, wenn der Musterraum übereinstimmt , und dann, genau wie beim anderen, Dbis zur ersten \newline elettiert und der Zyklus neu gestartet. Also mit Ihrer Beispieleingabe:
sed '$!N;/&/P;D' infile
Ausgänge:
aaaaaaaaa
bbbbbbbbb &
ccccccccc &
eeeeeeeee
fffffffff &
ggggggggg &
Um zu sehen, wie es funktioniert, fügen Sie lvor und nach dem hinzu N, um den Musterbereich zu betrachten:
sed 'l;$!N;l;/&/P;D' infile
zB mit einer Beispieldatei:
zzzz &
aaaa
bbbb
cccc &
dddd &
hhhh
eeee
ffff &
gggg &
Dies sind die Befehle, die sedausgeführt werden, und die entsprechende Ausgabe:
cmd Ausgabe cmd
l zzzz &$ N # read in the next line
l zzzz &\naaaa$ # pattern space matches so print up to \n
P zzzz & D # delete up to \n
l aaaa$ N # read in the next line
l aaaa\nbbbb$ D # delete up to \n (no match so no P)
l bbbb$ N # read in the next line
l bbbb\ncccc &$ # pattern space matches so print up to \n
P bbbb D # delete up to \n
l cccc &$ N # read in the next line
l cccc &\ndddd &$ # pattern space matches so print up to \n
P cccc & D # delete up to \n
l dddd &$ N # read in the next line
l dddd &\nhhhh$ # pattern space matches so print up to \n
P dddd & D # delete up to \n
l hhhh$ N # read in the next line
l hhhh\neeee$ D # delete up to \n (no match so no P)
l eeee$ N # read in the next line
l eeee\nffff &$ # pattern space matches so print up to \n
P eeee D # delete up to \n
l ffff &$ N # read in the next line
l ffff &\ngggg &$ # pattern space matches so print up to \n
P ffff & D # delete up to \n
l gggg &$ # last line so no N
l gggg &$ # pattern space matches so print up to \n
P gggg & D # delete up to \n