如何在 PowerShell 中查詢和替換文字檔案中的單詞?
為了在 PowerShell 中搜索並替換檔案中的單詞,我們將使用字串操作。事實上,PowerShell 中的 Get-Content 命令用於讀取幾乎任何型別的檔案內容。在本文中,我們考慮以下所示的一個文字檔案。
Get-Content C:\Temp\TestFile.txt
輸出
PS C:\> Get-Content C:\Temp\TestFile.txt # In case of linux, networkInterface names are of the form eth* # In Windows, please use the network full name from Device Manager networkInterfaces: ["Microsoft Hyper-V Network Adapter" ] overrideMetricsUsingScriptFile: false scriptTimeoutInSec: 60 scriptFiles: - osType: windows filePath: monitors/NetworkMonitor/scripts/windows-metrics.bat - osType: unixBase filePath: monitors/NetworkMonitor/scripts/unix-base-metrics.sh
以上輸出是檔案的內容,我們將對它進行操作。我們需要找到“NetWorkMonitor”這個詞並將其替換為“Active”。請注意,以上檔案是文字檔案,因此我們不需要將其轉換為字串,但如果存在任何其他副檔名,則可能需要使用 .ToString() 命令或 Out-String 方法將輸出轉換為字串,然後再執行任何操作。
現在,我們首先找到所需的字串,並讓我們使用 Select-String cmdlet 檢查需要替換多少行。
(Get-Content C:\Temp\TestFile.txt) | Select-String -Pattern "NetworkMonitor"
輸出
PS C:\> (Get-Content C:\Temp\TestFile.txt) | Select-String -Pattern "NetworkMonitor" filePath: monitors/NetworkMonitor/scripts/windows-metrics.bat filePath: monitors/NetworkMonitor/scripts/unix-base-metrics.sh
我們發現有兩行包含“NetworkMonitor”這個詞。我們需要使用以下命令替換該單詞。您也可以將 Get-Content 輸出儲存在變數中並在其上執行操作。
(Get-Content C:\Temp\TestFile.txt) -replace "NetworkMonitor","Active"
輸出
PS C:\> (Get-Content C:\Temp\TestFile.txt) -replace "NetworkMonitor","Active" # In case of linux, networkInterface names are of the form eth* # In Windows, please use the network full name from Device Manager networkInterfaces: ["Microsoft Hyper-V Network Adapter" ] overrideMetricsUsingScriptFile: false scriptTimeoutInSec: 60 scriptFiles: - osType: windows filePath: monitors/Active/scripts/windows-metrics.bat - osType: unixBase filePath: monitors/Active/scripts/unix-base-metrics.sh
上述命令替換了檔案內容,但尚未儲存,因此要儲存更新後的檔案,我們將使用 Set-Content 命令,最終程式碼如下:
(Get-Content C:\Temp\TestFile.txt) -replace "NetworkMonitor","Active" | Set-Content C:\Temp\Testfile.txt -Verbos
您也可以選擇不同的路徑來儲存檔案。如果檔案是隻讀的,則需要在 Set-Content cmdlet 中使用 -Force 引數。
廣告