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.
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.
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()
Import-CSV C:\Path\To\Original.csv | Select-Object Column1, Column3, Column2 | Export-CSV C:\Path\To\Newfile.csv
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With