未终止的's'命令

时间:2013-02-19 21:44:45

标签: perl sed

我正在处理一个perl脚本,该脚本会查找客户服务信息并更改服务ID。我现在的代码可以采用2列csv文件作为参考,并交换数字,但当我尝试使用“\ n”或“\ |”就像我需要的那样,它会给我'ol:

“sed:-e expression#1,char 29:unterminated`s s”

这是我的原始代码,用于更改引号中的数字:

#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV; #load Text::CSV module for parsing CSV
use LWP::Simple; #load LWP module for doing HTTP get

my $file = 'sid_swap.csv'; #CSV file to parse and load
my $csv = Text::CSV->new(); #create a new Text::CSV object

open (CSV, "<", $file) or die $!; #open CSV file for parsing

while (<CSV>) {
    if ($csv->parse($_)) {

        my @columns = $csv->fields(); #parse csv files and load into an array for each row
        my $newSID = $columns[0];
        my $oldSID = $columns[1];
        system("sed -i 's/\<row SERVICE_MENU_ID=\"$oldSID\"/\<row SERVICE_MENU_ID=\"$newSID\"/g' customer_data.txt");

    } else {
        my $err = $csv->error_input;
        print "Failed to parse line: $err";
    }
}
close CSV;

这是抛出错误的新代码:

#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV; #load Text::CSV module for parsing CSV
use LWP::Simple; #load LWP module for doing HTTP get

my $file = 'sid_swap.csv'; #CSV file to parse and load
my $csv = Text::CSV->new(); #create a new Text::CSV object

open (CSV, "<", $file) or die $!; #open CSV file for parsing

while (<CSV>) {
    if ($csv->parse($_)) {

        my @columns = $csv->fields(); #parse csv files and load into an array for each row
        my $newSID = $columns[0];
        my $oldSID = $columns[1];
        system("sed -i 's/\<row SERVICE_MENU_ID=\"$oldSID\"/\n$newSID\|/g' customer_data.txt");

    } else {
        my $err = $csv->error_input;
        print "Failed to parse line: $err";
    }
}
close CSV;

感谢您提供的任何帮助!

1 个答案:

答案 0 :(得分:4)

要进行调试,请将system("sed ...")更改为die("sed ...");。你会发现你正在尝试执行

sed -i 's/<row SERVICE_MENU_ID="OLDSID"/
NEWSID|/g' customer_data.t

我猜sed不喜欢其参数中间的实际换行符?这可以通过适当的逃避来修复,但你的方法是......疯了。您正在为CSV的每一行处理整个文件!

open(my $CSV, "<", $file) or die $!;    # Let's not use global vars!

my %fixes;
while (<$CSV>) {
    $csv->parse($_)
        or die "Failed to parse line: ".$csv->error_input."\n";

    my ($newSID, $oldSID) = $csv->fields();
    $fixes{$oldSID} = $newSID;
}

my $pat = join "|", map quotemeta, keys(%fixes);
my $re = qr/$pat/;

{
    local @ARGV = 'customer_data.txt';
    local $^I = '';  # "perl -i" mode
    while (<>) {
        s/<row SERVICE_MENU_ID="($re)"/\n$fixes{$1}|/g;
        print;
    }
}

一次性完成也解决了

的问题
1111,2222
2222,3333

相同
1111,3333
2222,3333