0

我的文件如下所示:

1  15
2  16
3  18
4  19
5  25
6  30
7  55
8  45
9  34
10 52

如果匹配的模式在第 6 行是 30,我想在第 6 行之前抓取 N 行,在第 6 行之后抓取 M 行,例如如果 N=3 和 M=4,那么结果应该是这样的:

3  18
4  19
5  25
6  30
7  55
8  45
9  34
10 52

我是 Perl 的新手,任何建议都将不胜感激。

﹟UPDATE 非常感谢下面这些有用的建议,我非常感谢他们。这是我的更新代码,欢迎提出任何建议!

my $num;

while(<>)
{   
if ( /pattern/) 
{$num = $. ;}   
}

open (,"") || die ("Can't open the file");

while(<>)

{
if (  $. >= $num-N and $. <=$num+M)
{    
print OUT "$_ \r";
}
}
4

2 回答 2

1

维护读取@preceding的最后几行的数组(我称之为)。N当模式匹配时,停止更新此数组并开始将行插入另一个数组 ( @following)。这样做直到@followingM行。

它应该看起来像这样(感谢 ikegami 现在已修复):

my $matched = 0;
my @preceding;
my @following;
while(<>){
    if ($matched){
        push ( @following, $_);
        last if @following == M;
        next;
    }
    else {
        push ( @preceding, $_);
        shift(@preceding) if @preceding > N;
    }
    $matched = 1 if /pattern/;
}
于 2013-05-06T02:17:07.810 回答
0
my @lines = <>;
foreach $idx (grep { $lines[$_] =~ /pattern/ } 0..$#lines) {
    print join (map {$lines[$_]} grep { $_ >= $idx - $B && $_ <= $idx +$A } 0..$#lines)."\n";
}

您也可以使用带有 -A,-B 标志的 GNU grep 命令来达到这个目的。

  -A NUM, --after-context=NUM
          Print NUM lines  of  trailing  context  after  matching  lines.
          Places  a  line  containing  --  between  contiguous  groups of
          matches.

   -B NUM, --before-context=NUM
          Print  NUM  lines  of  leading  context  before matching lines.
          Places a  line  containing  --  between  contiguous  groups  of
          matches.
于 2013-05-06T04:39:31.327 回答