Nathan Stohlmann Nathan Stohlmann - 3 months ago 14
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:

foo.bar=blah,blah,blah,bl\
ah,blah
foo2.bar=blah,blah,blah,b\
lah,blah


I want to unwrap those lines so that it becomes:

foo.bar=blah,blah,blah,blah,blah
foo2.bar=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.

Answer

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.