开发者

Using PowerShell to replace string that contains $ in the string

开发者 https://www.devze.com 2023-01-06 23:13 出处:网络
I am trying to use PowerShell do a simple find and replace. I use template text files and use $ in front of values that need to be changed.

I am trying to use PowerShell do a simple find and replace. I use template text files and use $ in front of values that need to be changed.

Example:

(Get-Content "D:\test") | Foreach-Object {$_ -replace "`$TBQUAL", "DBO"} | Set-Content "D:\test"

It should find the line OWNER=$TBQUAL and make it look like OWNER=DBO.

I am using the escape in front of $TBQUAL with no luck. To test that it 开发者_高级运维is working if I removed the $ from the front, it would replace TBQUAL and made it look like OWNER=$DBO.


Two things to get this to work:

  1. Use single quotes for your strings so that the $ is not interpreted as the start of a variable to be expanded.
  2. Escape the $ using a backslash "\" so the regular expression parser takes it literally.

For example,

PS C:\> 'Has a $sign in it' -replace 'a \$sign', 'no dollar sign'
Has no dollar sign in it


If you aren't using regular expressions in your replacement, you can do a simple (and fast) replace like this:

Foreach-Object {$_.Replace('$TBQUAL', 'DBO')}
0

精彩评论

暂无评论...
验证码 换一张
取 消