Here's how to emulate grep -B1
with sed
:
sed '$!N;/pattern/P;D' infile
It's very similar to the one here. Just like the other one, it reads in the N
ext line but this time, it P
rints up to first \n
ewline if the pattern space matches, and then, just like the other one, D
eletes up to first \n
ewline and restarts the cycle. So with your sample input:
sed '$!N;/&/P;D' infile
outputs:
aaaaaaaaa
bbbbbbbbb &
ccccccccc &
eeeeeeeee
fffffffff &
ggggggggg &
Again, to see how it works, add l
before and after the N
to look at the pattern space::
sed 'l;$!N;l;/&/P;D' infile
e.g. with a sample file:
zzzz &
aaaa
bbbb
cccc &
dddd &
hhhh
eeee
ffff &
gggg &
these are the commands that sed
executes and corresponding output:
cmd output 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