• 跳至主要導覽
  • 跳至主要內容
  • 跳至主要資訊欄
Office 指南

Office 指南

辦公室工作實用教學

  • Excel
  • Word
  • PowerPoint
  • Windows
  • PowerShell
  • R

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

介紹如何在 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,可以這樣寫:

# 將 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

分類:PowerShell

讀者互動方式

發佈留言 取消回覆

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

主要資訊欄

搜尋

近期文章

  • Linux 檢查、測試 CPU AES-NI 硬體加速加密指令集教學
  • CentOS Linux 7.9 自行編譯、安裝 OpenSSH 9.0p1 伺服器教學與範例
  • Python 使用 zipfile 模組壓縮、解壓縮 ZIP 檔案教學與範例
  • Python 以 LINE Notify 自動傳送即時訊息、圖片教學與範例
  • Linux 使用 Prometheus 與 Grafana 監控伺服器狀態、發送告警 Email 簡訊教學與範例
  • Linux 設定 pam_tty_audit 記錄 SSH 使用者操作指令教學與範例
  • Linux 封鎖、解鎖登入失敗次數過多的帳號 pam_faillock 教學與範例
  • Python 使用 pytube 自動下載 YouTube 影片教學與範例

推薦網站

  • Udemy 線上教學課程
  • Coursera 線上教學課程

關注本站

  • 電子郵件
  • Facebook

公益

  • 家扶基金會
  • 台灣世界展望會
  • Yahoo 奇摩公益
  • igiving 公益網
  • 兒福聯盟

Copyright © 2021 · Office Guide