将跟踪代码添加到CSV文件的每一行中的第一个链接实例

时间:2013-08-20 18:12:49

标签: regex perl

我想使用perl将跟踪代码添加到csv文件的每一行中的第一个链接实例。我怎么能这样做?

例如

输入:

ID, text1, link1, text2, text3, link2
1234, something, http://www.example.com/a/b/c, "lorem", "ipsum", http://www.example.com/image.gif
1235, something, http://www.example.com/dddd, "lorem", "ipsum", http://www.example.com/image.gif
1236, something, http://www.example.com/e/f/g/h, "lorem", "ipsum", http://www.example.com/image.gif

输出:

ID, text1, link1, text2, text3, link2
1234, something, http://www.example.com/a/b/c?tracking_code=1&tr2=2, "lorem", "ipsum", http://www.example.com/image.gif
1235, something, http://www.example.com/dddd?tracking_code=1&tr2=2, "lorem", "ipsum", http://www.example.com/image.gif
1236, something, http://www.example.com/e/f/g/h?tracking_code=1&tr2=2, "lorem", "ipsum", http://www.example.com/image.gif

1 个答案:

答案 0 :(得分:3)

使用Text::CSV正确处理CSV文件:

#!/usr/bin/perl
use warnings;
use strict;

use Text::CSV;

my $file = 'file.csv';

my $csv = 'Text::CSV'->new({allow_whitespace => 1,
                            eol => $/,
                           }) or die 'Text::CSV'->error_diag;
open my $CSV, '<', $file or die $!;

my $header = $csv->getline($CSV);
while (my $row = $csv->getline($CSV)) {
    $row->[2] .= '?tracking_code=1&tr=2';
    $csv->print(*STDOUT{IO}, $row);
}
$csv->eof or $csv->error_diag;