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