Search code examples
powershellpowershell-5.0

Replacing `,\r\n` in PowerShell


I'm trying to fix a CSV file that has a trailing ,\r\n in it. No matter what I do, it simply doesn't do anything. I tried putting the expression in [] which makes it replace every single comma. That implies that the issue is that it can't match the newline character.

I have saved the file with Windows line endings using Sublime Text, and have tried both variations of \r\n, \n\r, and just \n.

(Get-Content file.txt) | ForEach-Object { $_ -replace '\,\r\n', [System.Environmen
t]::NewLine } | Set-Content file2.txt

I'm using PowerShell version 5.1.15063.413


Solution

  • PowerShell turns out to be quite... special.

    Get-Content by default returns an array of strings. It finds all new line characters and uses them to split the input into said array. Meaning there are no new lines present for the regexp to match.

    A slight variation of this command using the -Raw parameter fixed my issue.

    (Get-Content file.txt -Raw).replace(",`r`n", [System.Environment]::NewLine) | Set-Content file2.txt