1

I must replace a value in a file. This works for normal text with this command

(Get-Content $file) | Foreach-Object {$_ -replace "SEARCH", "REPLACE"} | Set-Content $file

But now, the search text is "$(SEARCH)" (without quotes). Backslash escaping the '$' with '`$' doesn't work:

(Get-Content $file) | Foreach-Object {$_ -replace "`$(SEARCH)", "BLA"} | Set-Content $file

Any ideas? Thank you.

Macintron
  • 97
  • 1
  • 10

3 Answers3

2

The -replace operator is actually a regular expression replacement not a simple string replacement, so you've got to escape the regular expression:

(Get-Content $file) | Foreach-Object {$_ -replace '\$\(SEARCH\)', "BLA"} | Set-Content $file

Note that you can suppress string interpolation by using single quotes (') of double quotes (") around string literals, which I've done above.

Mike Zboray
  • 39,828
  • 3
  • 90
  • 122
  • 1
    Or better yet, `$_ -replace [regex]::escape('$(SEARCH)'), 'REPLACE'` since a lot of people aren't aware of how to properly escape a regex statement. – TheMadTechnician May 22 '15 at 05:30
  • @TheMadTechnician Or another option is string's Replace method: `$_.Replace('$(Search)', "BLA")`. – Mike Zboray May 22 '15 at 05:33
  • @Joey Sure there is. `$` is an anchor to a line ending. You have to escape it unless it appears inside a character set. – Mike Zboray May 22 '15 at 05:52
  • Ouch, I shouldn't comment before first tea in the morning. You're right of course. – Joey May 22 '15 at 05:58
0

Macintron,

You can try something like below :

(Get-Content $file) | Foreach-Object {$_.replace('$(SEARCH)', "BLA"} | Set-Content $file
GMaster9
  • 197
  • 1
  • 6
0

slightly (or even more) faster

sc $file ((gc $file -Raw) -replace '\$\(search\)','BLAHH')