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"
).