%% Colin Ingram <synergizedmusic@gmail.com> writes:
ci> This is not a debian specific question but I thought some of you
ci> could help. I am writing a shell script to parse a CSV file
Why would you choose bash to do this? The shell is great for running
commands, but it's really poor at parsing text, compared to
alternatives.
The most obvious is Perl, and you can even:
# apt-get install libtext-csv-perl
to install a Perl module that will parse CSV _for_ you, managing all the
quoting, escaping, etc.
I added
a stupid line to fix this but it breaks things if you have ", " in any
quoted field).
-------------------------------------------------------------------------------
#!/usr/bin/perl
use Text::CSV;
my $csv = Text::CSV_XS->new();
open(CSV, $ARGV[0]) or die "open: $ARGV[0]: $!\n";
while (defined ($_ = <CSV>)) {
# Valid CSV cannot have whitespace after commas--note this breaks if
# you have ", " inside a string... fix your CSV and remove this line!
s/, /,/;
$csv->parse($_) or warn("invalid CSV line: ", $csv->error_input(), "\n"), next;
my @fields = $csv->fields();
# Do something with the array... access it as $fields[0] ... $fields[n]
print "Fields: (@fields)\n";
}
close(CSV) or die "close: $ARGV[0]: $!\n";