• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
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

讀者互動

發佈留言 取消回覆

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

Primary Sidebar

搜尋

分類

Android Apple C/C++ Excel Linux OneNote PHP PowerPoint PowerShell Python R Windows Word 免費工具 創客 網站架設 線上工具 資料庫 遊戲 雜七雜八

近期文章

  • iCloud 匯入 Google 聯絡人教學
  • CSS 檔案最小化與壓縮處理教學與範例
  • Python 使用 ITK 讀取、寫入、建立影像教學與範例
  • Python 以 random 模組產生隨機亂數教學與範例
  • iPhone 手機開啟 VoLTE 與 WiFi 通話 VoWiFi 功能教學
  • Python 以 NumPy 的 unique 函數篩選陣列不重複元素教學與範例
  • ITK 計算 3D 二元遮罩影像物件數量與體積
  • SimpleITK 計算 2D 二元遮罩影像物件數量與統計值

推薦網站

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

關注本站

  • 電子郵件
  • Facebook

Copyright © 2020 · Office Guide