以下是如何模仿grep -B1
与sed
:
sed '$!N;/pattern/P;D' infile
这和这里的非常相似。就像另一个一样,它读取N
分机行,但是这一次,如果模式空间匹配,它会P
漂洗到第一条\n
ewline ,然后像另一条一样,删除到第一条ewline并重新启动循环。因此,使用您的示例输入: D
\n
sed '$!N;/&/P;D' infile
输出:
aaaaaaaaa
bbbbbbbbb &
ccccccccc &
eeeeeeeee
fffffffff &
ggggggggg &
同样,要查看其工作原理,请在l
之前和之后添加N
以查看模式空间::
sed 'l;$!N;l;/&/P;D' infile
例如带有示例文件:
zzzz &
aaaa
bbbb
cccc &
dddd &
hhhh
eeee
ffff &
gggg &
这些是sed
执行的命令和相应的输出:
cmd输出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