我需要删除文本文件字段中的换行符。例如:
输入文件如下所示:
"user1","John","Doe","123 a street,
San Francisco,
CA, 94089"
"user2","Foo","Bar","123 x rd., San Jose, CA 95129"
...
如何删除第一条记录中的换行符?
我需要删除文本文件字段中的换行符。例如:
输入文件如下所示:
"user1","John","Doe","123 a street,
San Francisco,
CA, 94089"
"user2","Foo","Bar","123 x rd., San Jose, CA 95129"
...
如何删除第一条记录中的换行符?
使用完整的错误检查:
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");
以下将实现这一点,尽管该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;
在 Perl 中,使用chomp
. 您可能想要 chomp 以逗号结尾的每一行:
perl -pe 'chomp if /,$/' input.txt
输入文件看起来像一个 CSV 文件。使用模块解析它可能会更好:Text::CSV