我需要刪除文本文件字段中的換行符。例如:使用Perl或shell腳本替換記錄中的換行符
輸入文件的樣子:
"user1","John","Doe","123 a street,
San Francisco,
CA, 94089"
"user2","Foo","Bar","123 x rd., San Jose, CA 95129"
...
如何刪除新行的第一個記錄?
我需要刪除文本文件字段中的換行符。例如:使用Perl或shell腳本替換記錄中的換行符
輸入文件的樣子:
"user1","John","Doe","123 a street,
San Francisco,
CA, 94089"
"user2","Foo","Bar","123 x rd., San Jose, CA 95129"
...
如何刪除新行的第一個記錄?
在Perl中,使用chomp
。您可能需要chomp以逗號結尾的每一行:
perl -pe 'chomp if /,$/' input.txt
輸入文件看起來像一個CSV文件。這可能是最好使用一個模塊來解析它:Text::CSV
以飽滿的錯誤檢查:
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;
爲什麼downvote? – ikegami
應該爲輸出打開$ fh_out(>); $ fn_ *!= $ fh_ +(關閉)。 –
@ Ekkehard.Horner,謝謝,修正。 – ikegami