1

I have this text file text.txt

aaa
#wsuri=myuri
ccc

and this command working OK

> "#wsuri=myuri" -replace '^#wsuri=myuri$','bbb'
bbb

But, if I try the same on a file:

> (Get-Content .\text.txt -raw) -replace '^#wsuri=myuri$','bbb'
aaa
#wsuri=myuri
ccc

What should I do for the regex to work on a file?

inquirymind
  • 135
  • 1
  • 11

2 Answers2

1

Due to use of Get-Content -Raw, your input string is a multiline string, but the ^ and $ regex anchors by default only operate on the start and end of the string as a whole, not on individual lines.

You have two options:

Include the Multiline regex option, which makes ^ and $ match the start and end of individual lines instead; its inline form - which must be placed at the start of the regex - is (?m):

(Get-Content .\text.txt -Raw) -replace '(?m)^#wsuri=myuri$','bbb'

Alternatively, for (slower) line-by-line input processing, which outputs an array of lines, simply omit -Raw:

(Get-Content .\text.txt) -replace '^#wsuri=myuri$','bbb'

Note that -replace, like all PowerShell comparison-like operators, accepts an array as the LHS, in which case the operation is performed on each element, which in this case means that each line from the input file is processed separately.

mklement0
  • 382,024
  • 64
  • 607
  • 775
-1

Try Setting set-content to the same file path:

((Get-Content -path .\text.txt -Raw) -replace '^#wsuri=myuri$','bbb') | Set-Content -Path .\text.txt
Ambrish Pathak
  • 3,813
  • 2
  • 15
  • 30
  • 1
    The problem isn't writing back to the same file, the problem is that `^` and `$` don't match _line_ beginnings and endings in a _multiline_ string (obtained with `Get-Content -Raw`) by default, so the `-replace` operation didn't work. – mklement0 Dec 04 '20 at 15:37