简体   繁体   中英

Replace a word in a string with powershell

I'm trying to replace the word of in a string, with a PowerShell script.

I have tried an if statement:

$string = "a tale of two cities "   

$array = $string -split " "    

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

The statement works at detecting of but I don't know how to replace it with a different word.

A single expression using the -replace operator is all you need:

> 'a tale of two cities' -replace '\bof\b', 'bob'
a tale bob two cities

If you want the resulting string split into words by whitespace:

$array = -split 'a tale of two cities' -replace '\bof\b', 'bob'

I find the method version a bit simpler:

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

Or even:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM