如何在powershell中将字符串替换为美元符号
在Powershell中,给定以下字符串如何在powershell中将字符串替换为美元符号,powershell,Powershell,在Powershell中,给定以下字符串 $string = "this is a sample of 'my' text $PSP.what do you think" 如何使用-replace函数将字符串转换为 this is a sample of 'my' text Hello.what do you think 我显然需要以某种方式转义字符串,而且$PSP不是我脚本中声明的变量 我需要将所有提到的$PSP更改为其他字符串您应该试试 $string=$string.Replace(“
$string = "this is a sample of 'my' text $PSP.what do you think"
如何使用-replace函数将字符串转换为
this is a sample of 'my' text Hello.what do you think
我显然需要以某种方式转义字符串,而且$PSP不是我脚本中声明的变量
我需要将所有提到的$PSP更改为其他字符串您应该试试
$string=$string.Replace(“\$PSP”,“Hello”)
或
$string=$string.Replace(“\$PSP”,$the\u new\u值)
或者更一般地使用正则表达式
$string=[regex]::Replace($string,\$\w+,“Hello”)
使用反勾号字符(在tab键上方): 要使用-replace运算符替换美元符号,请使用反斜杠将其转义:
"this is a sample of 'my' text `$PSP.what do you think" -replace '\$PSP', 'hello'
或者使用string.replace方法:
$string = "this is a sample of 'my' text `$PSP.what do you think"
$string.Replace('$PSP','Hello)'
这是“我的”文本Hello的一个示例。您认为如果不修改原始字符串(例如,通过转义$),这(实际上)是不可能的。 您的
$string
实际上不包含$PSP
,因为它在赋值语句中被零替换
$string = "this is a sample of 'my' text $PSP.what do you think"
$string -eq "this is a sample of 'my' text .what do you think"
评估结果为:
True
这是谷歌给出的第一个答案,尽管它确实很旧,所以我将添加我的细微变化
在我的例子中,我正在读取一个文件,并将其中的字符串替换为$s
我的文件的简短版本是:
<version>$version$<version>
这是一个文件读取(获取内容)过程,通过replace管道,并使用一组内容返回到文件。我可以这样做,但这是一个链式替换列表,这意味着更改此单个项目的格式。这实际可行吗?你测试过了吗?它对我不起作用是的,如果$string确实包含$character,它就起作用。当你检查输出时。(仅$string)您是否看到$PSP?我无法更改输入字符串我没有跟踪您,您从何处获取值?它来自sql脚本模板,该模板加载到变量中,那么您应该不会遇到用-replace或string.replace替换美元符号的问题。如果我从文本文件中读取值,则无法使用Sql进行测试。注意:同样有效的是“`$PSP”而不是“\$PSP”。当使用双引号以及使用反斜杠转义美元(对于正则表达式转义)时,您需要使用反勾号转义美元(对于PowerShell转义)。
<version>$version$<version>
(gc $fileName) | % { $_.replace('$version$', "$BuildNumber") } | sc $fileName