2014-06-19 20 views
0

我需要一些幫助來替換perl中兩個標記之間的行。我有,我想兩個標記之間修改行的文件:在perl中修改兩個標記之間的行

some lines 

some lines 

tag1 

ABC somelines 

NOP 

NOP 

ABC somelines 

NOP 

NOP 

ABC somelines 

tag2 

正如你所看到的,我有兩個標籤,標籤1和TAG2,基本上,我想與標籤1之間NOP更換ABC的所有實例和tag2。這是代碼的相關部分,但不能代替。任何人都可以請幫忙..?

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

回答

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

使用Flip-Flop運營商考慮一個班輪。

perl -i -pe 's/ABC/NOP/ if /^tag1/ .. /^tag2/' file 
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

相關問題