Berikut cara meniru grep -B1dengan sed:
sed '$!N;/pattern/P;D' infile
Ini sangat mirip dengan yang ada di sini . Sama seperti yang lain, ia membaca dalam Ngaris ext tetapi kali ini, ia Pmembentang ke \ngaris pertama jika ruang pola cocok , dan kemudian, seperti yang lain, Dmenghapus hingga \ngaris pertama dan memulai kembali siklus. Jadi dengan input sampel Anda:
sed '$!N;/&/P;D' infile
output:
aaaaaaaaa
bbbbbbbbb &
ccccccccc &
eeeeeeeee
fffffffff &
ggggggggg &
Sekali lagi, untuk melihat cara kerjanya, tambahkan lsebelum dan sesudah Nuntuk melihat ruang pola ::
sed 'l;$!N;l;/&/P;D' infile
misalnya dengan file sampel:
zzzz &
aaaa
bbbb
cccc &
dddd &
hhhh
eeee
ffff &
gggg &
ini adalah perintah yang sedmengeksekusi dan output yang sesuai:
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