这个user已经给出了你的答案,只是check here。
一些参考
在最简单的 sed 调用中,它在模式空间中有一行文本,即。输入中的 1 行 \n 分隔文本。模式空间中的单行没有 \n...这就是您的正则表达式找不到任何内容的原因。
您可以将多行读入模式空间并以惊人的方式操作事物,但付出的努力超出了正常范围。Sed 有一组命令允许这种类型的事情...这里是命令的链接sed 的总结。这是我找到的最好的,让我滚滚而来。
但是,一旦您开始使用 sed 的微命令,就会忘记“单线”的想法。将它像结构化程序一样布局是很有用的,直到你感觉到它......它非常简单,同样不寻常。您可以将其视为文本编辑的“汇编语言”。
总结:将 sed 用于简单的事情,也许更多,但一般来说,当它超出使用单行时,大多数人更喜欢其他东西......
我会让其他人提出其他建议。我真的不确定最好的选择是什么(我会使用 sed,但那是因为我不太了解 perl。)
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
这里是相同的脚本,浓缩成明显更难阅读和使用的脚本,但有些人会怀疑地称之为单行
sed '/^a test$/{$!{N;s/^a test\nPlease do not$/not a test\nBe/;ty;P;D;:y}}' alpha.txt
这是我的命令“备忘单”
: # label
= # line_number
a # append_text_to_stdout_after_flush
b # branch_unconditional
c # range_change
d # pattern_delete_top/cycle
D # pattern_ltrunc(line+nl)_top/cycle
g # pattern=hold
G # pattern+=nl+hold
h # hold=pattern
H # hold+=nl+pattern
i # insert_text_to_stdout_now
l # pattern_list
n # pattern_flush=nextline_continue
N # pattern+=nl+nextline
p # pattern_print
P # pattern_first_line_print
q # flush_quit
r # append_file_to_stdout_after_flush
s # substitute
t # branch_on_substitute
w # append_pattern_to_file_now
x # swap_pattern_and_hold
y # transform_chars