用管道替换逗号,而不是用双引号括起的逗号 [英] Replace commas with pipes, but not the commas enclosed in double quotes
本文介绍了用管道替换逗号,而不是用双引号括起的逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的记录集
I have a record set that looks like this
"BOSW0001","Mr","Wayne","Boswell","Wayne,Jessica & Lyn","31 Baker St"
"ELLI0007","Mrs","Bronwyn","Elliott","Bronwyn, Paul & Arianne","98A Dandaraga Rd"
"KENN0001","Mr","Leigh","Kenning","Leigh & Beth,Cole","22 Lake St"
我想用管道(,
> | ),而不替换
I want to replace the comma (,
) with pipe (|
) without replacing the comma inside of
"Leigh & Bethie,Coles"
"Waynez,Jessy & Lyne"
"Bronwynie, Paula & Arianne"
如何使用正则表达式或其他方法?
How can I do this using regular expression or other methods?
推荐答案
它与正则表达式;你使用一个合适的CSV解析器。这是一个(未测试的)示例,使用 Text :: CSV_XS - 在biz中最好的。
You don't do it with a regular expression; you do it with a proper CSV parser. Here's an (untested) example using Text::CSV_XS - the best in the biz.
use strict;
use warnings;
use Text::CSV_XS;
my $in_file = "whatever.csv";
my $out_file = "new.dat";
open my $fh, '<', $in_file or die "$in_file: $!";
open my $out_fh, '>', $out_file or die "$out_file: $!";
my $in_csv = Text::CSV_XS->new;
my $out_csv = Text::CSV_XS->new( { sep_char => '|', eol => "\n" } );
while( my $row = $in_csv->getline( $fh ) ) {
$out_csv->print( $out_fh, $row );
}
这篇关于用管道替换逗号,而不是用双引号括起的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文