Nathan Stohlmann Nathan Stohlmann - 1 year ago 141
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download