我正在嘗試從檔案中洗掉某些虛擬主機,其中有很多使用 bash。
例如。在我的腳本中,我想獲得使用 的虛擬主機the_one_known2.example.com,但又一次the_one_known3.example.com,即我想獲得一些部分形式的 apache 組態檔,其中包含在 bash 腳本中作為引數設定的預先已知的 URL(存在于 ServerName 或 ServerAlias 中)。
<VirtualHost *:80 *:${SERVER_PORT}>
ServerName test1.example.com
ServerAlias test2.example.com
ServerAlias the_one_known1.example.com
ServerAlias test3.example.com
</VirtualHost>
<VirtualHost *:80 *:${SERVER_PORT}>
ServerName test4.example.com
ServerAlias the_one_known2.example.com
ServerAlias test5.example.com
ServerAlias test6.example.com
</VirtualHost>
<VirtualHost *:80 *:${SERVER_PORT}>
ServerName the_one_known3.example.com
ServerAlias test7.example.com
ServerAlias test8.example.com
ServerAlias test9.example.com
</VirtualHost>
所以我的 URL 變數將更改為例如。the_one_known2.example.com我會得到:
<VirtualHost *:80 *:${SERVER_PORT}>
ServerName test4.example.com
ServerAlias the_one_known2.example.com
ServerAlias test5.example.com
ServerAlias test6.example.com
</VirtualHost>
[編輯] 到目前為止,我試圖找到選定虛擬主機的第一行:
url_line=$(grep -n -m 1 "${URL}" ./apache.conf" | sed 's/\([0-9]*\).*/\1/')
vitual_host_start_line="$((app_line-1))" // this is an assumption that Virtual Host starts just one line before the first occurance of URL
echo $vitual_host_line // the place it starts
但是我在找到這個虛擬主機的最后一行時遇到了問題,因為它是在</VirtualHost>之后的第一次出現vitual_host_start_line
uj5u.com熱心網友回復:
與awk:
awk -v name="the_one_known2.example.com" 'BEGIN{RS=ORS="</VirtualHost>\n"} $0~name{print; exit}' file
我假設the_one_known2.example.com您的檔案中沒有另一個域的子字串。
請參閱:8 個強大的 awk 內置變數——FS、OFS、RS、ORS、NR、NF、FILENAME、FNR
uj5u.com熱心網友回復:
使用您顯示的示例,請嘗試以下awk代碼。在 GNU 中撰寫和測驗awk。
awk -v RS='<VirtualHost[^/]*/' -v ORS="VirtualHost>\n" 'RT~/[[:space:]] the_one_known2\.example\.com\n/{print RT}' Input_file
解釋:簡單的解釋是,使 RS(記錄分隔符)從<VirtualHost直到下一次/出現(非貪婪匹配)。然后檢查它是否有[[:space:]] the_one_known2\.example\.com\n如果是然后列印匹配的值,這將VirtualHost>在段落結束時列印,因為它在程式中設定為 ORS 值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/379666.html
