PowerShell

PowerShell 搜尋、取代檔案內容教學與範例

介紹如何在 PowerShell 中使用 Get-ContentReplace 搜尋並取代檔案中的內容。

搜尋與取代

若要搜尋並取代檔案中的內容,可以先以 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,可以這樣寫:

# 將 file.txt 中的 the 取代為 THE
(Get-Content C:\file.txt).Replace('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 這樣的單字,可以改用正規表示法(regular expression)的方式,只匹配 the 這一的單字:

# 將 file.txt 中的 the 單字取代為 THE
(Get-Content C:\file.txt) -Replace('\bthe\b', '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 在正規表示法中視代表單字邊界(boundary)的意思,在 the 前後都加上 \b 就代表只匹配 the 這一個單字。

.Replace 方法函數跟 -Replace 運算子函數都可以用來進行文字的取代,用法也很類似,主要的差異在於 .Replace 只能使用單純的文字進行匹配,而 -Replace 則支援正規表示法。

儲存取代結果

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

# 將取代結果儲存至 C:\output.txt
(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

Share
Published by
Office Guide

Recent Posts

Python 使用 PyAutoGUI 自動操作滑鼠與鍵盤

本篇介紹如何在 Python ...

9 個月 ago

Ubuntu Linux 以 WireGuard 架設 VPN 伺服器教學與範例

本篇介紹如何在 Ubuntu ...

9 個月 ago

Linux 網路設定 ip 指令用法教學與範例

本篇介紹如何在 Linux 系...

9 個月 ago

Windows 使用 TPM 虛擬智慧卡保護 SSH 金鑰教學與範例

本篇介紹如何在 Windows...

10 個月 ago

Linux 以 Shamir’s Secret Sharing 分割保存金鑰教學與範例

介紹如何在 Linux 中使用...

11 個月 ago

Linux 以 Cryptsetup、LUKS 加密 USB 隨身碟教學與範例

介紹如何在 Linux 系統中...

11 個月 ago