I have some huge (2GB and more) CSV files I need to sort, using Powershell or Perl (company request). I need to sort them from any column, depending on the file.
My CSV files are, for some, looking like this, using double quotes :
Column1;Column2;Column3;Column4
1234;1234;ABCD;"1234;ABCD"
5678;5678;ABCD;"5678;ABCD"
9012;5678;ABCD;"9012;ABCD"
...
In Powershell, I already tested the solution Import-CSV, but I got OutOfMemory Exception problem. I also tried to load my CSV file in SQL table using OleDb Connection with this code :
$provider = (New-Object System.Data.OleDb.OleDbEnumerator).GetElements() | Where-Object { $_.SOURCES_NAME -like "Microsoft.ACE.OLEDB.*" }
if ($provider -is [system.array]) { $provider = $provider[0].SOURCES_NAME } else { $provider = $provider.SOURCES_NAME }
$csv = "PathToCSV\file.csv"
$firstRowColumnNames = "Yes"
$connstring = "Provider=$provider;Data Source=$(Split-Path $csv);Extended Properties='text;HDR=$firstRowColumnNames;';"
$tablename = (Split-Path $csv -leaf).Replace(".","#")
$sql = "SELECT * from [$tablename] ORDER BY Column3"
# Setup connection and command
$conn = New-Object System.Data.OleDb.OleDbconnection
$conn.ConnectionString = $connstring
$conn.Open()
$cmd = New-Object System.Data.OleDB.OleDBCommand
$cmd.Connection = $conn
$cmd.CommandText = $sql
$cmd.ExecuteReader()
# Clean up
$cmd.dispose
$conn.dispose
But this returns me the error :
Exception calling "ExecuteReader" with "1" argument(s): "No value given for one or more required parameters." and I don't understand why. I tried to modify the code, the SQL code, and it still doesn't work.
I think this is the best solution to do that, but I didn't achieve to make it work for now, and I'm open to all other solutions that could work...
I'm a total beginner in Perl, so I just tried to understand how it works and how to use it, but didn't code anything for the moment.
EDIT
I just tested all the solutions you proposed, and thank you very much for this help.
Both solutions didn't work because the modules you told me to use (Text::CSV, File::Sort or Data::Dumper) are not installed in the Perl version I am using, and I can't install them (company restrictions...).
What I've tried instead, is to try a simple sort on a column, without taking care of the double quotes problem :
use CGI qw(:standard);
use strict;
use warnings;
my $file = 'path\to\my\file.csv';
open (my $csv, '<', $file) || die "cant open";
foreach (<$csv>) {
chomp;
my @fields = split(/\;/);
}
@sorted = sort { $a->[1] cmp $b->[1] } @fields;
I was thinking this should work, sorting in my array @sorted the datas I have by the 2nd column, but it doesn't work, and I don't understand why...