文章目录[隐藏]
介绍如何在PowerShell 中使用 Get-Content
Replace
搜寻与取代
若要搜寻并取代档案中的内容,可以先以 Get-Content
Replace
假设 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.
若要把所有的 the
THE
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.
这里会将所有 the
THE
the
weather
the
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.
这里的 \b
the
\b
the
.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
讀者互動
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。