Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell script to replace commas within double quotes with nothing

Tags:

powershell

csv

I have a comma separated CSV file, where I intend to replace the commas in double quotes to nothing and also replace double quotes with nothing:

Editor's note: The original form of this question asked to "change [the] delimiter to pipe" (|), which is no longer a requirement; gms0ulman's answer was written when it still was.

$inform = Get-Content C:\test.csv
$inform | % { 
$info = $_.ToString().Replace(",","") 
$var = $info 
$var | Out-file C:\test1.csv -Append 
}

Any help would be much appreciated.

In:

1,2,"Test,ABC"

Out:

1,2,TestABC
like image 876
Joseph Avatar asked Jan 01 '26 10:01

Joseph


2 Answers

Import the CSV. Convert it to a CSV with a different delimiter. Replace the commas. Convert the delimiter back. Replace the double quotes. Write out the resulting file.

Import-Csv -Path C:\MyFile.csv |
    ConvertTo-Csv -Delimiter '|' | 
    ForEach-Object { $_ -replace ',',[String]::Empty } | 
    ConvertFrom-Csv -Delimiter '|' | 
    ConvertTo-Csv |
    ForEach-Object { $_ -replace -replace '"',[String]::Empty } |
    Set-Content -Path C:\MyFile_fixed.csv
like image 135
Bacon Bits Avatar answered Jan 03 '26 00:01

Bacon Bits


I would break this down into two steps. Another StackOverflow user may be able to give you a one-liner.

Import-Csv C:\test.csv | Export-Csv tempfile.csv -Delimiter "|"
(Get-Content tempfile.csv).Replace(",","").Replace('"',"") | Out-File test1.csv
like image 33
G42 Avatar answered Jan 02 '26 23:01

G42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!