Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use powershell to reorder CSV columns

Tags:

powershell

csv

Input file:

column1;column2;column3
data1a;data2a;data3a
data1b;data2b;data3b

Goal: output file with reordered columns, say

column1;column3;column2
...

UPDATED Question: What is a good way of using powershell to solve this problem. I am aware of the existence of CSV related cmdlets, but these have limitations. Note that the order of records does not need to be changed, so loading the entire input/output file in memory should not be needed.

like image 429
Bernard Vander Beken Avatar asked Jun 17 '11 13:06

Bernard Vander Beken


People also ask

How do I redirect a PowerShell output to a CSV file?

To do this we can use the Export-CSV function in PowerShell. The Export-CSV function converts PowerShell objects into a CSV string and saves them into a CSV file. If you only need a CSV string, then you can also use the ConvertTo-CSV function in PowerShell.


2 Answers

Here is the solution suitable for millions of records (assuming that your data do not have embedded ';')

$reader = [System.IO.File]::OpenText('data1.csv')
$writer = New-Object System.IO.StreamWriter 'data2.csv'
for(;;) {
    $line = $reader.ReadLine()
    if ($null -eq $line) {
        break
    }
    $data = $line.Split(";")
    $writer.WriteLine('{0};{1};{2}', $data[0], $data[2], $data[1])
}
$reader.Close()
$writer.Close()
like image 89
Roman Kuzmin Avatar answered Sep 28 '22 10:09

Roman Kuzmin


Import-CSV C:\Path\To\Original.csv | Select-Object Column1, Column3, Column2 | Export-CSV C:\Path\To\Newfile.csv
like image 22
EBGreen Avatar answered Sep 28 '22 11:09

EBGreen