【问题标题】:modify lines between two tags in perl修改perl中两个标签之间的行
【发布时间】:2014-06-19 22:55:19
【问题描述】:

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

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

【问题讨论】:

    标签: perl


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      $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

      【讨论】:

        【解决方案3】:

        你写的$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

        【讨论】:

          猜你喜欢
          • 2022-11-24
          • 1970-01-01
          • 2015-08-11
          • 2017-01-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-20
          • 1970-01-01
          相关资源
          最近更新 更多