CSV形式に変換するPerlスクリプト
rpt2csv.pl aaaa.rpt
みたいに使用する
#!/usr/bin/perl
use strict;
use utf8;
use File::BOM qw/open_bom/;
if ( $#ARGV < 0 ) {
print "$0 <rpt file>\n";
print "output filename is <rpt file>.csv\n";
exit;
}
my $filename = $ARGV[0];
open INFILE, "<:via(File::BOM)", $filename or die "cannot open $filename";
open OUTFILE, ">:utf8", $filename. ".csv" or die "cannot open $filename.csv";
$/ = "\r\n";
print "$filename:\t";
my $titleline = <INFILE>;
chomp $titleline;
my $lengthline = <INFILE>;
chomp $lengthline;
my @length_tmp = split / /, $lengthline;
$lengthline = undef;
my @length;
for (my $i=0; $i < $#length_tmp; $i++){
$length[$i] = length $length_tmp[$i];
}
print OUTFILE txt2csv($titleline) , "\r\n";
$titleline = undef;
my $counter = 0;
my $counter_length = 0;
$| = 1;
while (<INFILE>){
$counter++;
chomp $_;
print OUTFILE txt2csv($_) , "\r\n";
if ($counter % 100 == 0){
print "\b" x $counter_length;
$counter_length = length $counter;
print $counter;
}
}
print "\b" x $counter_length;
print $counter , "\n";
close INFILE;
close OUTFILE;
exit;
sub txt2csv($){
my $line = shift @_;
my @items = ();
my $str = undef;
for (my $i=0; $i < $#length; $i++){
$str = substr($line, 0, $length[$i]);
substr($line, 0, $length[$i]+1) = "";
$str =~ s/^\s*//go;
$str =~ s/\s*$//go;
push @items, $str;
}
return join ',', map {(s/"/""/g or /[\r\n,]/) ? qq("$_") : $_} @items;
}
0 件のコメント:
新しいコメントは書き込めません。