perl regex中的反向引用

时间:2015-05-07 16:38:31

标签: regex perl

我的输入文件包含以下内容:

India ;91;0,1684
India Mobile ;9174;0,1630
India Fix ;9122;0,3345

我想追加&#34 ;; MOB"到第二行,以便输出如下所示

India ;91;0,1684
India Mobile ;9174;0,1630;MOB
India Fix ;9122;0,3345

我编写了一个perl脚本,尝试使用正则表达式执行此操作:

open FILE, $ARGV[0] or die "Can't open data";
@lines = <FILE>;
close FILE;

foreach(@lines) {
    chomp;
    s/(.* Mobile .*)/$1;MOB/;
    print $_ . "\n";
}

但这会产生如下输出:

India ;91;0,1684
;MOBa Mobile ;9174;0,1630
India Fix ;9122;0,3345   

有人可以指导我在这里找到的那​​个小小技巧是什么?

1 个答案:

答案 0 :(得分:4)

您的输入数据似乎包含回车{ "data": [ { "ACTIVITY_NAME": "Test", "children": [ { "ACTIVITY_NAME": "Test", "MAINTENANCE_GROUP": "1", "START_DATE": "04/30/2015", "END_DATE": "05/01/2015", "COMPLETED": "10", "TOTAL": "15" }, { "ACTIVITY_NAME": "Test", "MAINTENANCE_GROUP": "2", "START_DATE": "04/30/2015", "END_DATE": "05/01/2015", "COMPLETED": "20", "TOTAL": "25" } ] }, { "ACTIVITY_NAME": "Test2", "children": [ { "ACTIVITY_NAME": "Test2", "MAINTENANCE_GROUP": "1", "START_DATE": "05/2/2015", "END_DATE": "05/03/2015", "COMPLETED": "30", "TOTAL": "35" }, { "ACTIVITY_NAME": "Test2", "MAINTENANCE_GROUP": "1", "START_DATE": "05/2/2015", "END_DATE": "05/03/2015", "COMPLETED": "40", "TOTAL": "45" }, { "ACTIVITY_NAME": "Test2", "MAINTENANCE_GROUP": "1", "START_DATE": "05/2/2015", "END_DATE": "05/03/2015", "COMPLETED": "50", "TOTAL": "55" } ] } ] } 。在输入上运行\r,然后运行脚本。它应该按预期工作。

说明:您的替换有效,但由于您的数据有回车符,因此输出变为dos2unix
回车将光标移动到行的开头,并在显示时开始过度键入。这就是为什么您的输出行似乎是India Mobile ;9174;0,1630\r;MOB - 实际上;MOBa Mobile过度输入了India Mobile