我必須用 Powershell 替換文本檔案中的字串。文本檔案具有以下內容:
app.framework.locale=de_DE
app.gf.data.profile=somevalues,somevalues[,...]
app.gf.data.profile.path=C:\somepath\somesubpath
app.basket.currencies=currencies
我想設定組態檔和 profile.path。因此,無論“=”后面的字串有多長,都應該替換“=”后面的所有內容。
我正在讀取檔案,替換字串,并使用以下命令寫回檔案:
更改個人資料:
(Get-Content $TXT_FILE ).Replace('app.gf.data.profile=default,',"app.gf.data.profile=default,$Man") | Out-File $TXT_FILE -Encoding ASCII
更改組態檔路徑:
(Get-Content $TXT_FILE ).Replace('app.gf.data.profile.path=',"app.gf.data.profile.path=$Path") | Out-File $TXT_FILE -Encoding ASCII
如您所見,我的替換腳本不正確,“=”后面的其余部分將保留。我想我需要一個正則運算式或某種通配符來滿足我的需求。
uj5u.com熱心網友回復:
你需要使用
(Get-Content $TXT_FILE) `
-replace '^(app\.gf\.data\.profile=).*', "`$1,$Man" `
-replace '^(app\.gf\.data\.profile\.path=).*', "`${1}$Path" | `
Out-File $TXT_FILE -Encoding ASCII
這里,-replace用于啟用正則運算式替換,兩個正則運算式都遵循類似的邏輯:
^- 匹配一行的開頭(app\.gf\.data\.profile=)- 將文字字串(正則運算式中的文字點必須轉義)捕獲到組 1($1或${1}).*- 匹配該行的其余部分。
${1}在第二種情況下使用,因為變數$Path緊跟在反向參考之后,如果它以數字開頭,則替換將不會像預期的那樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/362080.html
