3

我在 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 的虚拟主机。

我试图在 sed 中做到这一点,但我没有得到任何帮助..有什么帮助吗?

这是我到目前为止...

sed '/^[ \t]*<VirtualHost/,/^[ \t]*<\/VirtualHost/{
/^ServerName/!{
   /<VirtualHost/{
     /^/a\ServerName abc.com

   }
  }
}' httpd.conf
4

3 回答 3

2

使用 sed:

sed '/<VirtualHost/{
       :a N;/<\/VirtualHost>/!b a;
       /ServerName/!s!\(</VirtualHost>\)!ServerName abc.com\n\1!
}' input

对于这个特定问题,我认为 awk 与 sed 相比没有任何优势。

于 2013-04-11T21:28:18.357 回答
1

我认为也许 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
于 2013-04-11T20:33:34.587 回答
0

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
}
于 2013-04-11T20:39:58.667 回答