2015-10-13 72 views
1

我想匹配“current_line ABC/123”和通过只是保持“尺寸”字符串属于它删除它下面ins_bug属于它。如果Current_line不是abc/123,我想打印所有内容。如何匹配字符串,并删除指定的字符串使用Perl

输入

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
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#) {$_=""} 
+0

这是一个了不起的解释。我试过了,它为我工作。对我来说它的一个很好的学习 – SKG

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 $_; 
} 
+0

也会尝试这种方法。非常感谢 – SKG

+0

IMO这样的范围运营商比设置一个标志更好。 – Sobrique

相关问题