Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - Replacing a string with a variable ending with a dollar sign

I'm a bit lost with this one. For whatever reason the replace function in powershell doesn't play well with variables ending with a $ sign.

Command:

$var='A#$A#$'
$line=('$var='+"'"+"'")
$line -replace '^.+$',('$line='+"'"+$var+"'")

Expected output:

$line='A#$A#$'

Actual output:

$line='A#$A#
like image 557
Brad.Smith Avatar asked May 19 '26 10:05

Brad.Smith


1 Answers

It looks like you're getting hit with a regex substitution that you don't want. The regex special variable $' represents everything after your match. Since your regex matches the entire string, $' is effectively empty. During the replace operation, the .Net regex engine sees $' in your expected output and substitutes in that empty string.

One way to avoid this is to replace all instances of $ in your $var string with $$:

$line -replace '^.+$',('$line='+"'"+($var.Replace('$','$$'))+"'")

You can see more information about regex substitution in .Net here:

Substitutions

like image 144
ajk Avatar answered May 21 '26 04:05

ajk