編輯 INI 檔案特定部分的幾行

編輯 INI 檔案特定部分的幾行

我有 subversion 設定檔 ( ~/.subversion/servers)

我需要修改以新增代理程式資訊(主機、連接埠、例外)。該文件包含許多帶有代理資訊的部分。我只想修改[全球的]

我已經為此創建了一個正則表達式,但它不起作用。

/(\[global\].*[\n])((.*[\n])*)([\s\#]*http-proxy-port\s?=\s?.*)/gm

您可以嘗試線上測試https://regex101.com/它非常適合替換為:

\1\2http-proxy-port=9000

我嘗試sed執行上面的行,但沒有任何提示。

sed -i -r 's/(\[global].*[\n])((.*[\n])*)([\s\#]*http-proxy-port\s?=\s?.*)/\1\2http-proxy-port=9000/gm' \
 ~/.subversion/servers

我怎麼能使用sed上面的正規表示式?

此範例顛覆檔案:

### The currently defined server options are:
###   http-proxy-host            Proxy host for HTTP connection
###   http-proxy-port            Port number of proxy host service
###   http-proxy-username        Username for auth to proxy service
###   http-proxy-password        Password for auth to proxy service
###   http-proxy-exceptions      List of sites that do not use proxy
###   http-timeout               Timeout for HTTP requests in seconds

[groups]
# group1 = *.collab.net
# othergroup = repository.blarggitywhoomph.com
# thirdgroup = *.example.com

### Information for the first group:
# [group1]
# http-proxy-host = proxy1.some-domain-name.com
# http-proxy-port = 80
# http-proxy-username = blah
# http-proxy-password = doubleblah
# http-timeout = 60

### Information for the second group:
# [othergroup]
# http-proxy-host = proxy2.some-domain-name.com
# http-proxy-port = 9000

### SSL certificate.  See details above for overriding security
### due to SSL.
[global]
# http-proxy-exceptions = *.domain.org, *.domain.com
# http-proxy-host = proxy.domain.com
# http-proxy-port = 8080
# http-proxy-username = defaultusername
# http-proxy-password = defaultpassword

預期輸出將是

...
[global]
http-proxy-exceptions = *.otherdomain.org, *.otherdomain.com, 127.0.0.1, localhost
http-proxy-host = proxy.otherdomain.com
http-proxy-port = 9000
# http-proxy-username = defaultusername
# http-proxy-password = defaultpassword

答案1

正如建議的那樣,有更好的方法來編輯 INI 文件……
不過,這是一種方法sed

sed '/^\[.*\]/h
/http-proxy-exceptions/{x;/\[global\]/!{x;b;};x;c\
http-proxy-exceptions = *.otherdomain.org, *.otherdomain.com, 127.0.0.1, localhost
}
/http-proxy-host/{x;/\[global\]/!{x;b;};x;c\
http-proxy-host = proxy.otherdomain.com
}
/http-proxy-port/{x;/\[global\]/!{x;b;};x;c\
http-proxy-port = 9000
}' infile

每次遇到行匹配時,都會用模式空間內容覆蓋保持緩衝區[.*](即將每個節名稱保存到h舊緩衝區中)。在與您的模式相符的每一行上,http-.*它都會x更改緩衝區 - 如果保留空間確實如此不是( !) 匹配[global],然後它x變回並通過 跳到下一個循環b。如果保持空間匹配,則[global]x會變回並c掛起模式空間的內容。

相關內容