• 跳至主要導覽
  • 跳至主要內容
  • 跳至主要資訊欄
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

讀者互動方式

發佈留言 取消回覆

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

主要資訊欄

搜尋

近期文章

  • C++ 語言使用 Crypto++ 實作 RSA 數位簽章教學與範例
  • C++ 語言使用 Crypto++ 實作 RSA-OAEP 搭配 SHA256 加密教學與範例
  • C++ 語言使用 Crypto++ 實作 AES 加密、解密、認證加密教學與範例
  • C++ 語言使用 Crypto++ 實作 MD5、SHA1、SHA2、BLAKE2 雜湊教學與範例
  • Ubuntu Linux 安裝、使用 Crypto++ 加密函式庫教學與範例
  • C 語言使用 OpenSSL 實作橢圓曲線 ECDH 金鑰交換教學與範例
  • Python 以 eciespy 實作 ECC 非對稱式加密方法教學與範例
  • C 語言使用 OpenSSL 實作 PBKDF2 教學與範例

推薦網站

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

關注本站

  • 電子郵件
  • Facebook

公益

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

Copyright © 2021 · Office Guide