简体   繁体   English

sed - 匹配多行并在匹配上方插入

[英]sed - matching multiple lines and insert above the match

I have a file that looks like this 我有一个看起来像这样的文件

#multi
#line
#comment
$var1=foo

#multi
#line
#comment
$var2=bar

#############################################
#   END                                     #
#############################################

using sed (since i am already using sed in other places in my script and i would prefer to remain consistent) how can I match the "END" section ie one or more comment marks followed by a coment + space + END and then add the following lines before the end section 使用sed(因为我已经在我的脚本的其他地方使用了sed,我宁愿保持一致)如何匹配“END”部分,即一个或多个注释标记后跟一个cament + space + END然后添加在结束部分之前的以下行

#############################################
# user login
#############################################

server.user=$USER
server.pswd=$PASSWD

<newline>
<newline>

please comment you answer so I can learn and hopefully not need to ask a followup question 请评论你回答所以我可以学习,希望不需要问一个后续问题

thanks ! 谢谢 !

 sed '/^##* END$/i\
# user login\
#############################################\
\
server.user=$USER\
server.pswd=$PASSWD\
\
\
#############################################' input

This takes advantage of the fact that the header block of the END section is only one line and is the same as the header of the inserted block so that we are re-using the first line of the END section as the first line of the header of the new section, and writing a new first line for the END block header. 这利用了以下事实:END部分的标题块只有一行,并且与插入块的标题相同,因此我们重新使用END部分的第一行作为标题的第一行新部分,并为END块头写一个新的第一行。 The i command tells sed to insert text before the buffer is printed, and the escaped newlines allow us to insert multiple lines of text. i命令告诉sed在打印缓冲区之前插入文本,并且转义的换行符允许我们插入多行文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM