如何匹配字符串并使用Perl删除属于它的指定字符串

时间:2015-10-13 03:56:19

标签: perl

我想匹配" current_line abc / 123"并通过保持"尺寸"去除下面的ins_bug。字符串属于它。如果Current_line不是abc / 123,我想打印所有内容。

输入

  current_line
  current_line  abc/123/187/
  ins_bug       {[sgd/hsjfk/123]}
  size          hkjd/hkjdjl/hjkj


 current_line
 current_line  dsfd
 ins_bug       {[hds/hdf/123]}
 size          kjfgkf/hkdjf

 current_line
 current_line  ahd/ijk/
 ins_bug       {[sgd/hsjfk/123]}

 current_line
 current_line  abc/123/jhk/
 ins_bug      {[hk/hsjfk/123]}
 ins_bug      {[hkcd/1235/465]}
 size         jfkdjgfdl/hkshfhd
 ins_bug      {[hdkc/563/545]}
 size          kjfhgkfjglf/hskahfjd

 current_line
 current_line  hjkd
 ins_bug       {[hds/hdf/123]}
 size          djfkljlg/hkdsgj
 ins_bug       [dsf/dfdg/dfdfd]
 size          dklgfks/jdskljfldlk

 current_line
 current_line  abc/123/897
 ins_bug       dgds/hsgds/412
 size         jkjfd/kjdjf

输出

current_line
current_line  abc/123/187/

size    hkjd/hkjdjl/hjkj


 current_line
 current_line  dsfd
 ins_bug      {[hds/hdf/123]}
 size          kjfgkf/hkdjf

 current_line
 current_line  ahd/ijk/
 ins_bug      {[hkj/hsjfk/123]}

 current_line
 current_line  abc/123/jhk/
 size          jfkdjgfdl/hkshfhd
 size          kjfhgkfjglf/hskahfjd

 current_line
 current_line  hjkd
 ins_bug       {[hds/hdf/123]}
 size          djfkljlg/hkdsgj
 ins_bug       [dsf/dfdg/dfdfd]
 size          dklgfks/jdskljfldlk

 current_line
 current_line  abc/123/jkjjkj
 size          jkjfd/kjdjf

我试着写这段代码

CODE:

#!/usr/bin/env perl

use warnings;
use strict;

open (fh, "sas.txt" );
open (OUT, " > out.txt");

$x = 0;
my $mat = qr/abc\/123/;

while ($line = <fh>)
{
    chomp ($line);
    if ($line =~ m/current_line/)
    {
         print OUT "$line \n";
         $x = 1;
    }
    elsif ($x == 1)
    {
         if ($line =~ m/$mat/)
         {
              print OUT " $line \n" unless $line =~ m/ins_bug/; 
         }
    }
    else
    {
          print OUT " $line \n ";
    }
}
close (fh);

2 个答案:

答案 0 :(得分:4)

使用..范围运算符可以删除大量代码。以下是在脚本框架内使用它的方法:

use strict;
use warnings;

# use lexical file handles
open my $fh_in, '<', 'sas.txt'
    or die "Could not open input file";
open my $fh_out, '>', 'out.txt'
    or die "Could not open output file";

while(<$fh_in>) {
    # use the .. range operator (see perldoc op) to only
    # match lines between and including the two patterns
    if (m!current_line\s+abc/123!..m!^\s*$!) {
        next if /ins_bug/;
    }

    print $fh_out $_;
}

答案 1 :(得分:2)

cat sas.txt | perl -pe 'BEGIN {$abc=0} m#(current_line)\s+(abc/123)?#; if ($1) { $abc=$2 ? 1 : 0 } if ($abc && m#ins_bug#) {$_=""}' > out.txt

如果我们在“abc / 123”部分,请跟踪。

BEGIN {$abc=0}

匹配current_line部分,可选地匹配abc / 123。

m#(current_line)\s+(abc/123)?#;

如果我们匹配abc / 123,请将其标记,否则取消标记。

if ($1) { $abc=$2 ? 1 : 0 }

当在abc / 123部分时,如果我们遇到“ins_bug”行,请跳过它。

if ($abc && m#ins_bug#) {$_=""}