修改perl中两个标签之间的行

时间:2014-06-19 22:55:20

标签: perl

我需要一些帮助来更换perl中两个tages之间的行。我有一个文件,我想修改两个标签之间的行:

some lines

some lines

tag1

ABC somelines

NOP

NOP

ABC somelines

NOP

NOP

ABC somelines

tag2

正如你所看到的,我有两个标签,tag1和tag2,基本上,我想在tag1和tag2之间用NOP替换ABC的所有实例。这是代码的相关部分,但不替代。谁能请帮忙..?

        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);

3 个答案:

答案 0 :(得分:2)

使用Flip-Flop运算符考虑单线程。

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

答案 1 :(得分:1)

$INPLACE_EDIT与范围运算符..

结合使用
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;

有关编辑文件的其他方法,请查看:perlfaq5

答案 2 :(得分:0)

您的$line = s/ABC/NOP/;行不正确,您需要=~

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