簡體   English   中英

使用sed將缺少的ServerName添加到httpd.conf文件

[英]Add missing ServerName to httpd.conf file using sed

我在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

使用sed:

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

對於這個特殊的問題,我認為awk沒有比sed有任何優勢。

我認為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

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM