Text::CSV を使ってみる

  • Text::CSV をインストールする。
$ /usr/local/bin/cpanm -f Text::CSV
  • text_csv_sample.pl
#!/usr/bin/env perl
use strict;
use warnings;
use Text::CSV;
my $tc = Text::CSV->new;
while(<>){
    next unless $tc->parse($_);
    my @fields = $tc->fields;
    print join("\t", @fields), "\n";
}
__END__
"a1","b1","c1"
"b1","b""2","b3"
"c1","c2","c3"
  • 実行してみる。
$ chmod 755 text_csv_sample.pl
$ ./text_csv_sample.pl text_csv_sample.csv
a1      b1      c1
b1      b"2     b3
c1      c2      c3

カンマがタブに変換されている。

参考


追記:
ちょっと作ってみたスクリプトのソース。

  • convert_sqlcud_csv.sh
#!/usr/bin/bash
export LANG=C
ls org/*.csv|while read FILE_PATH
do
	FILE_NAME=$(basename ${FILE_PATH})
	./convert_sqlcud_csv.pl org/${FILE_NAME} > mod/${FILE_NAME}
done
  • convert_sqlcud_csv.pl
#!/usr/bin/env perl
use strict;
use warnings;
use Text::CSV;
my $tc = Text::CSV->new;
while(<>){
	next if ($. <= 3 or ! $tc->parse($_));
	my @fields = $tc->fields;
	print join(",", map{ $_=qq/\"$_\"/; } @fields[0,1,15,5,6,9,10,16,17,4]), "\n" if $#fields >= 17;
}
__END__