简体   繁体   中英

How to match above and below lines, then insert words in between them by using Perl?

How to match special characters and multiple lines at the same time? Then insert text in between those matched lines. I would like to match lines - Sample ("xx"),direction:north and market_fall ("when_promotion_8X10_b05afn10ld0b0") { as shown below. Then print text after line color code:0.000;. My coding seems wrong in somewhere. Could anyone give guidance? Thank you..

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") {  

My coding:

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

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

Try following perl one-liner from shell

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

EDIT

If you must use it within a perl script try following piece of code.

#!/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

I like abiessu's suggestion. Here is some sample code:

#!/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;
      }
    }

given the input:

a
b
c
start1
start2
d
e

You will get:

a
b
c
start1
start1
Inserted Text
start2
d
e

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM