0

如何同时匹配特殊字符和多行?然后在这些匹配的行之间插入文本。我想匹配行 - Sample ("xx"),direction:north and market_fall ("when_promotion_8X10_b05afn10ld0b0") { 如下所示。然后在行颜色代码:0.000;之后打印文本。我的编码在某处似乎是错误的。有人可以指导吗?谢谢..

Sample ("apple") {
direction : north ;
      I dont want this line+: ;
      I dont want this line^ ;
      No this line : line ;
      color code: 0.000;
      I dont want this line: (c*b)+(c*a)+(b*a))" ;
      max_price : 3.6;
      min_price : 1.2;
      I dont want this line_time() {
        I dont want this line_t_sense : positive_1 ;
        No_this line either  : "c" ;
        market_fall ("when_promotion_8X10_b05afn10ld0b0") {  

我的编码:

if(my $line =~ m/Sample(" ")/ & /direction : north/ & /market_fall ("when_promotion_8X10_b05afn10ld0b0") {/ ){    #match specific line

        print "aa\n";                 #print words at previous line
}
}
4

2 回答 2

0

我喜欢abiessu的建议。这是一些示例代码:

#!/usr/bin/perl

my $l1;
my $l2;

    while( my $line = <> ){
      $l1 = $l2;
      $l2 = $line;

        if( $l1 =~ /start1/ && $l2 =~ /start2/ ){
            print $l1;
            print "Inserted Text\n";
            print $l2;
      }
      else {
            print $l2;
      }
    }

给定输入:

a
b
c
start1
start2
d
e

你会得到:

a
b
c
start1
start1
Inserted Text
start2
d
e
于 2013-11-01T15:11:42.240 回答
0

尝试从外壳perl跟踪单行

perl -0777 -pe 's/(Sample\s*\("[^"]+"\)\s*\{.*direction\s*:\s*\w+\s*;.*color\s*code:\s*0.000;)(.*market_fall\s*\("[^"]+"\))/$1\nLineYouWantToInsert$2/gs' file

编辑

如果您必须在perl script尝试以下代码中使用它。

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

open my $fh, '<', 'file' or die $!;
my $line = do { local $/; <$fh> };
$line =~ s/(Sample\s*\("[^"]+"\)\s*\{.*direction\s*:\s*\w+\s*;.*color\s*code:\s*0.000;)(.*market_fall\s*\("[^"]+"\))/$1\nLineYouWantToInsert$2/gs;
print $line;
close $fh
于 2013-11-01T15:07:12.877 回答