匹配单词PERL后跳过特定行数

时间:2013-09-25 06:30:04

标签: perl lines

我希望匹配文件中的特定行,在匹配特定行后,我想跳过5行并打印下一行。 E.g。

Lecture       <==(I want to match lecture)
1
2
3
4
5
Hello   <==(And then i want to print this line)

我尝试过这样做,但它无法正常工作:

if ($line =~ m/(Lecture)/) {
    $1 = $currentLine;
    if ($currentLine == $1+6) {
        print $currentLine;
    }
}

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您可以使用变量$.来跟踪匹配发生的行号,并跳过所需的行数。话说:

perl -ne '/^Lecture/ && do {$l=$.} ; $.==$l+6 && print' inputfile

会在匹配后打印第6行(在这种情况下会生成Hello)。

答案 1 :(得分:0)

#/usr/bin/perl
use strict;
use warnings;

open my $fh, '<', 'data.txt' or die "can't open data.txt: $!";

while (my $line = <$fh> ) {
    if ($line =~ /Lecture/) { #if a match is found ...   
        <$fh> foreach 1 .. 5; # throw away next five lines from iterator 
        my $next_line = <$fh>; # assign next one
        print $next_line;       # and print it
    }
}