user2812535
user2812535

Reputation: 13

modify lines between two tags in perl

I need some help with replaceing lines between two tages in perl. I have a file in which I want to modify lines between two tags:

some lines

some lines

tag1

ABC somelines

NOP

NOP

ABC somelines

NOP

NOP

ABC somelines

tag2

As you can see, I have two tags, tag1 and tag2 and basically, I want to replace all instances of ABC with NOP between tag1 and tag2. Here is the relevant portion of code but it doesn't replace. Can anyone please help..?

        my $fh;
        my $cur_file = "file_name";
        my @lines = ();
        open($fh, '<', "$cur_file") or die "Can't open the file for reading $!";
        print "Before while\n";
        while(<$fh>)
        {
            print "inside while\n";
            my $line = $_;
            if($line =~ /^tag1/)
            {
                print "inside range check\n";
                $line = s/ABC/NOP/;
                push(@lines, $line);
            }
            else
            {
                push(@lines, $line);
            }

        }
        close($fh);

        open ($fh, '>', "$cur_file") or die "Can't open file for wrinting\n";
        print $fh @lines;
        close($fh);

Upvotes: 0

Views: 129

Answers (3)

Chankey Pathak
Chankey Pathak

Reputation: 21666

Your line which says $line = s/ABC/NOP/; is incorrect, you need =~ there.

#!/usr/bin/perl
use strict;
use warnings;
my $tag1 = 0;
my $tag2 = 0;
while(my $line = <DATA>){
    if ($line =~ /^tag1/){
        $tag1 = 1; #Set the flag for tag1
    }
    if ($line =~ /^tag2/){
        $tag2 = 1; #Set the flag for tag2
    }
    if($tag1 == 1 && $tag2 == 0){
        $line =~ s/ABC/NOP/;    
    }
    print $line;
}

Demo

Upvotes: 0

hwnd
hwnd

Reputation: 70732

Consider a one-liner using the Flip-Flop operator.

perl -i -pe 's/ABC/NOP/ if /^tag1/ .. /^tag2/' file

Upvotes: 2

Miller
Miller

Reputation: 35198

Use $INPLACE_EDIT in conjunction with the range operator ..

use strict;
use warnings;

local $^I = '.bak';
local @ARGV = $cur_file;
while (<>) {
    if (/^tag1/ .. /^tag2/) {
        s/ABC/NOP/;
    }
    print;
}
unlink "$cur_file$^I"; #delete backup;

For alternative ways to edit a file, check out: perlfaq5

Upvotes: 1

Related Questions