我希望匹配文件中的特定行,在匹配特定行后,我想跳过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;
}
}
我做错了什么?
答案 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
}
}