sed '/^a test$/{ $!{ N # append the next line when not on the last line s/^a test\nPlease do not$/not a test\nBe/ # now test for a successful substitution, otherwise #+ unpaired "a test" lines would be mis-handled t sub-yes # branch_on_substitute (goto label :sub-yes) :sub-not # a label (not essential; here to self document) # if no substituion, print only the first line P # pattern_first_line_print D # pattern_ltrunc(line+nl)_top/cycle :sub-yes # a label (the goto target of the 't' branch) # fall through to final auto-pattern_print (2 lines) } }' alpha.txt
指令
命令 功能 a 在当前行后添加一行或多行 c 用此符号后的新文本替换当前行中的文本 i 在当前行之前插入文本 d 删除行 h 把模式空间里的内容复制到暂存缓冲区 H 把模式空间里的内容追加到暂存缓冲区 g 把暂存缓冲区里的内容复制到模式空间,覆盖原有的内容 G 把暂存缓冲区的内容追加到模式空间里,追加在原有内容的后面 l 列出非打印字符 p 打印行 n 读入下一输入行,并从下一条命令而不是第一条命令开始对其的处理 N 读入下一输入行,并从第一条命令开始对其的处理 (当前处理是2行的内容) q 结束或退出sed r 从文件中读取输入行 ! 对所选行以外的所有行应用命令 s 用一个字符串替换另一个 g 在行内进行全局替换 w 将所选的行写入文件 x 交换暂存缓冲区与模式空间的内容 y 将字符替换为另一字符(不能对正则表达式使用y命令)
删除指定行的上一行下一行 sed -i -e :a -e '$!N;s/.*\n\(.*linuxeye.com\)/\1/;ta' -e 'P;D' test.txt