簡體   English   中英

用powershell替換字符串中的單詞

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM