0

我需要删除文本文件字段中的换行符。例如:

输入文件如下所示:

"user1","John","Doe","123 a street,
San Francisco,
CA, 94089"
"user2","Foo","Bar","123 x rd., San Jose, CA 95129"
...

如何删除第一条记录中的换行符?

4

3 回答 3

1

使用完整的错误检查:

use Text::CSV_XS qw( );

my $qfn_in  = '...'; 
my $qfn_out = $qfn_in . '.new';

my $csv = Text::CSV_XS->new({
    binary => 1,
    eol    => "\n",
});

open(my $fh_in, "<:encoding(UTF-8)", $qfn_in)
   or die("Can't open \"$qfn_in\": $!\n");

open(my $fh_out, ">:encoding(UTF-8)", $qfn_out)
   or die("Can't create \"$qfn_out\": $!\n");

while (my $row = $csv->getline($fh)) {
   s/\n/ /g for @$row;
   $csv->print($fh, $row) 
      or die("Error writing to \"$qfn_out\": " . $csv->error_diag() . "\n");
}

$csv->eof()  
   or die("Error reading \"$qfn_in\": " . $csv->error_diag() . "\n");

close($fh_in);
close($fh_out) 
   or die("Error writing to \"$qfn_out\": $!\n");

rename($qfn_out, $qfn_in) 
   or die("Can't overwrite \"$qfn_in\" with \"$qfn_out\": $!\n");
于 2012-10-01T23:38:22.677 回答
0

以下将实现这一点,尽管该Text::CSV_XS解决方案更加健壮:

use strict;
use warnings;


my $str =<<"DATA";
"user1","John","Doe","123 a street,
San Francisco,
CA, 94089"
"user2","Foo","Bar","123 x rd., San Jose, CA 95129"
DATA

$str =~ s/,\n/,/g;

print $str;
于 2012-10-02T16:51:08.180 回答
0

在 Perl 中,使用chomp. 您可能想要 chomp 以逗号结尾的每一行:

perl -pe 'chomp if /,$/' input.txt

输入文件看起来像一个 CSV 文件。使用模块解析它可能会更好:Text::CSV

于 2012-10-01T23:36:48.590 回答