2

In Powershell Script, how do I convert a | (pipe) delimited CSV file to a , (comma) delimited CSV file?

When we use the following command in Windows Powershell Encoding 'UTF8' -NoType to convert from | (pipe delimiter) to , (comma delimiter), the file is converted with , delimited but the string was surrounded by " " (double quotes). Like given below:

Source file data:

ABC|1234|CDE|567|

Converted file data:

"ABC","1234","CDE","567",

I want to generate the following:

ABC,1234,CDE,567,

What command can I use to convert the delimiter from | to ,?

Stevoisiak
  • 20,148
  • 23
  • 110
  • 201

5 Answers5

3

I would use:

(Get-Content -Path $file).Replace('|',',') | Set-Content -Path $file
E. Jaep
  • 1,841
  • 1
  • 29
  • 50
2

You must escape the pipe, so:

(get-content "d:\makej\test.txt" ) -replace "\|","," | set-content "d:\makej\test.csv"
Floern
  • 32,709
  • 24
  • 103
  • 117
zajbo
  • 21
  • 1
1

Seems easy enough:

(get-content $file) -replace '|',',' | set-content $file
mjolinor
  • 62,812
  • 6
  • 108
  • 130
0

Sorry this may need some tweaking on your part, but it does the job. Note that this also changes the file type from .txt to .csv which I dont think you wanted.

$path = "<Path>"
$outPath = $path -replace ".txt",".csv"
Get-Content -path $path | 
ForEach-Object {$_ -replace "|","," } |  
Out-File -filepath $outPath
ricky89
  • 1,196
  • 5
  • 21
  • 37
0

I view the suggested answers as a little risky, because you are getting the entire contents of the existing file into memory, and therefore won't scale well, and risks using a lot of memory. My suggestion would be to use the string replace as the previous posts suggested, but to use streams instead for both reading and writing. That way you only need memory for each line in the file rather than the entire thing.

Have a look here at one of my other answers here: https://stackoverflow.com/a/32337282/380016

And in my sample code you'd just change the string replace to:

$s = $line -replace '|', ','

And also adjust your input and output filenames accordingly.

Community
  • 1
  • 1
campbell.rw
  • 1,326
  • 10
  • 21