我必须在特定的虚拟主机块中添加一行
<VirtualHost *:80>
#
#Existing Lines
#
#--New line should go here
</VirtualHost>
sed 脚本应该使得该行不应该被添加到任何其他虚拟主机块中。
我必须在特定的虚拟主机块中添加一行
<VirtualHost *:80>
#
#Existing Lines
#
#--New line should go here
</VirtualHost>
sed 脚本应该使得该行不应该被添加到任何其他虚拟主机块中。
一种使用方式sed
。它选择 和 之间的行<VirtualHost *:80>
,</VirtualHost>
并在最后一个中插入文本。
sed -e '/^<VirtualHost[ ]\*:80>/,/<\/VirtualHost>/ { /<\/VirtualHost>/ i\NEW TEXT' -e '}'
一个例子:
假设下一个内容为infile
:
<VirtualHost more:80>
#
#Existing Lines
#
#--New line should go here
</VirtualHost>
<VirtualHost *:80>
#
#Existing Lines
#
#--New line should go here
</VirtualHost>
<VirtualHost *:8080>
#
#Existing Lines
#
#--New line should go here
</VirtualHost>
像这样运行它:
sed -e '/^<VirtualHost[ ]\*:80>/,/<\/VirtualHost>/ { /<\/VirtualHost>/ i\NEW TEXT' -e '}' infile
具有以下输出:
<VirtualHost more:80>
#
#Existing Lines
#
#--New line should go here
</VirtualHost>
<VirtualHost *:80>
#
#Existing Lines
#
#--New line should go here
NEW TEXT
</VirtualHost>
<VirtualHost *:8080>
#
#Existing Lines
#
#--New line should go here
</VirtualHost>
<VirtualHost url="server:port">
如果满足上述条件,请检查以下内容:
kent$ cat vh.txt
<VirtualHost url="bar:80">
<bar>i am virtualHost bar</bar>
</VirtualHost>
<VirtualHost url="here:80">
#
#Existing Lines
#
</VirtualHost>
<VirtualHost url="foo:80">
<foo>i am fooo</foo>
</VirtualHost>
kent$ awk '/<VirtualHost url="here:80">/&& !x{x=1;print;next;}/<\/VirtualHost>/&&x==1{$0="NEW_NEW\n"$0;x=2}1' vh.txt
<VirtualHost url="bar:80">
<bar>i am virtualHost bar</bar>
</VirtualHost>
<VirtualHost url="here:80">
#
#Existing Lines
#
NEW_NEW
</VirtualHost>
<VirtualHost url="foo:80">
<foo>i am fooo</foo>
</VirtualHost>
上面的 awk onliner 将新行“NEW_NEW”添加到正确的 VirtualHost 元素。