Nathan Stohlmann Nathan Stohlmann - 10 months ago 56
PowerShell Question

How do I replace a backslash and newline character in sequence using regular expressions in Powershell?

Say I have a file of text where lines have been wrapped deliberately. Each wrapped line ends with a backslash character '\' and then a newline. Example:,blah,blah,bl\

I want to unwrap those lines so that it becomes:,blah,blah,blah,blah,blah,blah,blah,blah

Currently when I attempt to do this using the following command I get no matches and thus no changes:

( Get-Content .\somefile.txt | Out-String ) -replace '\\\n',''

If I use either '\' or '\n' it replaces either the backslash or the newline, but when used together it produces no matches.


If it's a Windows style line ending, then it's a carriage return and a linefeed, so 0xD0XA or \r\n. If you want to handle both possibilities:

-replace '\\\r?\n',''

So basically, the backslash \\ followed by an optional carriage return \r? followed by a linefeed \n.