0

I'm trying to remove the new line on the first match of "three", but I'm not sure why the below example isn't working:

$var = 'one two three
four five six
seven'

$var = $var.replace("three`n", 'three ')
$var

Desired output:

one two three four five six
seven
zihobu
  • 37
  • 3
  • To potential close voters: The problem _is_ reproducible, namely in script files that use CRLF newlines. – mklement0 Jun 26 '21 at 23:16

1 Answers1

2

To account for variations in newline (line-break) formats, use the -replace operator with regex \r?\n to match a newline in a platform- / file-format-neutral manner:

$var = 'one two three
four five six
seven'

$var -replace 'three\r?\n', 'three '

The regex \r?\n matches both Windows-format CRLF (\r\n) and Unix-format LF (\n only) newlines.

The foregoing uses verbatim regex escape sequences, which the .NET regex engine underlying the -replace operator interprets. Expressed as PowerShell escape sequences inside expandable strings ("..."), the newline formats are `r`n and `n.
You could also express the last statement as $var -replace "three`r?`n", 'three ', but it's generally better to pass verbatim strings ('...') to the .NET regex engine, so as to avoid confusion over what PowerShell interprets, up front, vs. what the .NET regex engine interprets.

Note that it is your script file's newline format that determines the newline format of multiline string literals in it, so if your script file uses CRLF newlines, "three`n" will not match, because the LF ("`n") in the input string is preceded by a CR ("`r").

mklement0
  • 382,024
  • 64
  • 607
  • 775