0

我想匹配文件中的特定行,在匹配特定行后,我想跳过 5 行并打印下一行。例如

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

我究竟做错了什么?

4

2 回答 2

2

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

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

将在匹配后打印第 6 行(在本例中为 generate Hello)。

于 2013-09-25T06:41:38.873 回答
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
    }
}
于 2013-09-25T15:12:24.850 回答