介绍如何在PowerShell 中使用 Get-ContentReplace

搜寻与取代

若要搜寻并取代档案中的内容,可以先以 Get-ContentReplace

假设 C:\file.txt

Whether the weather be fine or whether the weather be not.
Whether the weather be cold or whether the weather be hot.
We'll weather the weather whether we like it or not.

若要把所有的 theTHE


WheTHEr THE weaTHEr be fine or wheTHEr THE weaTHEr be not.
WheTHEr THE weaTHEr be cold or wheTHEr THE weaTHEr be hot.
We'll weaTHEr THE weaTHEr wheTHEr we like it or not.

这里会将所有 theTHEtheweatherthe


Whether THE weather be fine or whether THE weather be not.
Whether THE weather be cold or whether THE weather be hot.
We'll weather THE weather whether we like it or not.

这里的 \bthe\bthe

.Replace方法函数跟 -Replace.Replace-Replace

储存取代结果

上面的取代結果會直接輸出在螢幕上,如果希望可以將這些結果儲存下來,可以在後方加上一個 Set-Content 並指定儲存的檔案名稱:

(Get-Content C:\file.txt) -Replace('\bthe\b', 'THE') | Set-Content C:\output.txt

這樣就會將取代的結果儲存至 C:\output.txt

取代原始檔案

如果希望將取代的結果直接儲存至原來的檔案之中,將原本的舊內容覆蓋掉,只要將輸出的檔案名稱設定為輸入檔案的名稱即可:

(Get-Content C:\file.txt) -Replace('\bthe\b', 'THE') | Set-Content C:\file.txt

這樣就可以將取代的結果直接儲存至原來的 C:\file.txt 檔案中。

參考資料:Adam the Automator

讀者互動

 

Oh 游读者 👋
It’s nice to meet you.

每周三,您都将收到一封内容详实的Newsletter.

close

Oh 游读者 👋
It’s nice to meet you.

每周三,您都将收到一封内容详实的Newsletter.