Grobanix
Grobanix

Reputation: 169

Issue finding and replacing regex in Powershell

I have an ini file that looks like this:

[list_text]                       
text_002=L-Win+3=Regards\nThomas

I try to find and replace the "\nThomas" with a different name:

$settings = Get-Content -Raw $path -Encoding UTF8
$settings = $settings -replace '`r`nThomas', '\nMike'

I tested different ways trying to find the "\nThomas" but nothing seems to work.

Upvotes: 0

Views: 56

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175085

The pattern "`r`n..." will look for a literal carriage return and newline characters.

You aren't looking for any of those, you're looking for the verbatim escape sequence \n. To describe a backslash in a regex pattern, escape it with another backslash:

$settings -replace '\\nThomas', '\nMike'

You can also use [regex]::Escape() to escape any given verbatim string:

$settings -replace ([regex]::Escape('\nThomas')), '\nMike'

Upvotes: 3

Related Questions