Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 940
Jacobm001 Avatar asked Mar 09 '23 15:03

Jacobm001


1 Answers

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
like image 188
Jacobm001 Avatar answered Mar 17 '23 06:03

Jacobm001