您可以尝试使用perl 及其Text::CSV_XS 模块:
#!/usr/bin/env perl
use warnings;
use strict;
use Text::CSV_XS;
my (@columns);
open my $fh, '<', shift or die;
my $csv = Text::CSV_XS->new or die;
while ( my $row = $csv->getline( $fh ) ) {
undef @columns;
if ( @$row <= 12 ) {
@columns = @$row;
next;
}
my $extra_columns = ( @$row - 12 ) / 2;
my $post_columns_index = 4 + 2 * $extra_columns * 2;
@columns = (
@$row[0..3],
(join( '', @$row[4..(4+$extra_columns)] )) x 2,
@$row[$post_columns_index..$#$row]
);
}
continue {
$csv->print( \*STDOUT, \@columns );
printf "\n";
}
假设输入文件 (infile) 有三行,其中第一个有一个额外的逗号,第二个有两个额外的逗号,第三个是正确的:
2011,123456,1234567,12345678,Hey There,How are you,Hey There,How are you,882864309037,ABC ABCD,LABACD,1.00000000,80.2500000,One Two
2011,123456,1234567,12345678,Hey There,How are you,now,Hey There,How are you,now,882864309037,ABC ABCD,LABACD,1.00000000,80.2500000,One Two
2011,123456,1234567,12345678,Hey There:How are you,Hey There:How are you,882864309037,ABC ABCD,LABACD,1.00000000,80.2500000,One Two
像这样运行脚本:
perl script.pl infile
产生:
2011,123456,1234567,12345678,"Hey ThereHow are you","Hey ThereHow are you",882864309037,"ABC ABCD",LABACD,1.00000000,80.2500000,"One Two"
2011,123456,1234567,12345678,"Hey ThereHow are younow","Hey ThereHow are younow",LABACD,1.00000000,80.2500000,"One Two"
2011,123456,1234567,12345678,"Hey There:How are you","Hey There:How are you",882864309037,"ABC ABCD",LABACD,1.00000000,80.2500000,"One Two"
请注意,它添加了一些引号,但它基于 csv 规范是正确的,并且更容易处理之前的状态。