我在httpd.conf文件中有以下虚拟主机
<VirtualHost *:80> ## could be comments could be any line could be any line could be any line </VirtualHost> <VirtualHost *:80> could be any line ## could be comments could be any line could be any line could be any line could be any line could be any line </VirtualHost> <VirtualHost *:80> ## may have comments ServerName ppp.com could be any line could be any line could be any line </VirtualHost> <VirtualHost *:443> ## could be empty ServerName zzz.com could be any line could be any line could be any line </VirtualHost>
我试图将“ServerName abc.com”添加到没有已经设置了ServerName的每个虚拟主机。
我试图在SEED做,我没有得到任何帮助?
这是我迄今为止…
sed '/^[ \t]*<VirtualHost/,/^[ \t]*<\/VirtualHost/{ /^ServerName/!{ /<VirtualHost/{ /^/a\ServerName abc.com } } }' httpd.conf
我想可能awk更适合这个任务。 这里是add-server-name.awk
:
/<VirtualHost/ { named=0; indent=substr($0,1,match($0,/<VirtualHost/)-1) } /^[[:blank:]]*serverName[[:blank:]]*/ { named=1; } /<\/VirtualHost>/ { if (!named) print indent "serverName abc.com" } { print }
用法:
awk -f add-server-name.awk httpd.conf
使用sed:
sed '/<VirtualHost/{ :a N;/<\/VirtualHost>/!ba; /serverName/!s!\(</VirtualHost>\)!serverName abc.com\n\1! }' input
我不认为awk对于这个特殊问题比sed有什么优势。
awk将会是一个更好的帮助。 它处理多行更好,再加上httpd.conf已经是一个记录格式。
# adserver.awk BEGIN { RS = "</VirtualHost>" } #separate records on end of a Virtual Host $0 /serverName/ { print $0 $RS} # used for records with a name $0 ~ /serverName/ { # else for ( i = 1; i <= NF; i ++ ) { print $i if ( $i /<VirtualHost.*>/ ) { print "serverName abc.com\n" } } print $RS }