2017-04-12 59 views
0

我試圖用PowerShell腳本替換字符串中的單詞of用PowerShell替換字符串中的單詞

我試圖if語句:

$string = "a tale of two cities " 

$array = $string -split " "  

if($array -match 'of') { 
    $array -replace 'bob' 
} 

聲明工作在檢測of但我不知道如何用不同的詞替換它。

+1

您應該經常檢查文檔,也可能檢查一些關於您遇到問題的命令的網頁。對於這個問題,我建議你看看['Get-Help about_Comparison_Operators'](https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_comparison_operators)和[此腳本專家專欄](https://blogs.technet.microsoft.com/heyscriptingguy/2011/03/21/use-powershell-to-replace-text-in-strings/)。 –

回答

1

使用-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' 
+0

是否有可能將世界替換爲「of」在數組中並測試數組中的單詞列表?像:$ array = $ array -replace $ wordList –

+0

@williamyocom:不,'-replace'只支持RHS上的一個字符串。我建議你問一個新問題(一旦你這樣做,請隨時讓我知道)。 – mklement0

0

我找對方法的版本簡單一點:

"a tale of two cities ".Replace('of','bob') 

甚至:

$string = "a tale of two cities " 
$string.Replace('of','bob') 
+0

是的,在這種特殊情況下,.NET類的'.Replace()'_method_執行的_literal_替換更簡單,但通常PowerShell基於_regex_的'-replace' _operator_更加靈活。 – mklement0