[英]Replace a word in a string with powershell
我想替換的單詞of
一個字符串,用PowerShell腳本。
我嘗試了一個if語句:
$string = "a tale of two cities "
$array = $string -split " "
if($array -match 'of') {
$array -replace 'bob'
}
該語句可以檢測到of
但是我不知道如何用其他單詞替換它。
您只需要使用-replace
運算符的單個表達式即可:
> 'a tale of two cities' -replace '\bof\b', 'bob'
a tale bob two cities
如果希望將結果字符串用空格分割成多個單詞:
$array = -split 'a tale of two cities' -replace '\bof\b', 'bob'
我發現方法版本更簡單:
"a tale of two cities ".Replace('of','bob')
甚至:
$string = "a tale of two cities "
$string.Replace('of','bob')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.