我正在使用perl通过以下命令将逗号分隔的文件转换为制表符分隔的文件:
perl -e ' $sep=","; while(<>) { s/\Q$sep\E/\t/g; print $_; } warn "Changed $sep to tab on $. lines\n" ' csvfile.csv > tabfile.tab
但是,我的文件还有其他逗号,我不想在特定的列中将其分开。这是我的文件的示例:
ADNP, "descript1, descript2", 1
PTB, "descriptA, descriptB", 5
我只想将引号外的逗号转换为制表符,如下所示:
ADNP descript1, descript2 1
PTB descriptA, descriptB 5
无论如何,可以使用perl,python或bash进行此操作吗?
在Perl中琐碎,使用Text::CSV
:
#!/usr/bin/env perl
use strict;
use warnings;
use Text::CSV;
#configure our read format using the default separator of ","
my $input_csv = Text::CSV->new( { binary => 1 } );
#configure our output format with a tab as separator.
my $output_csv = Text::CSV->new( { binary => 1, sep_char => "\t", eol => "\n" } );
#open input file
open my $input_fh, '<', "sample.csv" or die $!;
#iterate input file - reading in 'comma separated'
#printing out (to stdout -can use filehandle) tab separated.
while ( my $row = $input_csv->getline($input_fh) ) {
$output_csv->print( \*STDOUT, $row );
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句