在行尾前填写空数据

Fill in empty data before end of line

我正在处理一些 CSV 文件。最后一个字段有时会丢失数据,如下所示: first,last John,Smith Francis,

这会在尝试加载到数据库时导致摄取错误。我想在最后一个逗号之后、crlf 之前添加一个 space 或其他一些 'filler',但我无法用 search/replace 填充它。例如,我尝试了以下操作: $data =~ s/,\x0d\x0a/,\x20\x0d[=14=]xa/gi 但在 crlf 之前没有添加 space。 当然,我需要保留行尾以便正确标记行。

我试过使用 Path::Tiny 和通用 open 阅读,但到目前为止没有成功。

第一:使用一个模块来处理csv文件,一个好的是Text::CSV

现在,对于这样的工作,这一次,一个简单的过滤器就可以了:

my $line = q(first,last John,Smith Francis,);

$line =~ s/.*,\K$/filled_last_field/; 

贪婪的 .* 匹配行中以下模式(此处为逗号)的 last 实例。 \K form of the positive lookbehind 删除所有以前的匹配项,这样它们就不会被消耗;所以它只替换它后面的模式(在这种情况下,根据需要添加短语)。

如果您想先替换文件,然后逐行读取文件并将更改的行写入新文件,然后将其移到旧文件上。

open my $fh, '<', $file or die "Can't open $file: $!";
open my $fh_out, '>', $new_file or die "Can't open $new_file: $!";

while (<$fh>) {
    print $fh_out s/.*,\K$/filled_last_field/r;
}
# Move $new_file to $file

我在其中使用 /r modifier, which returns the modified string, just right for the print here. See and (例如)来获取此类具有相关详细信息的完整程序。

或者,用 Path::Tiny

path($file)->edit_lines( sub { s/.*,\K$/ADDED/ } )

0.077版本增加了直接编辑文件的方法。该模块的许多方法都有对应的 _utf8,还有 edit_lines_utf8


单行

perl -wpe's/.*,\K$/ADDED/' file.csv > new_file.csv

或者,更改输入文件就地

perl -i -wpe's/.*,\K$/ADDED/' file.csv

或者,更改它并保留备份

perl -i.bak -wpe's/.*,\K$/ADDED/' file.csv