在匹配单词PERL后跳过特定数量的行
我想匹配文件中的特定行,匹配特定行后,我想跳过5行并打印下一行。例如在匹配单词PERL后跳过特定数量的行,perl,lines,Perl,Lines,我想匹配文件中的特定行,匹配特定行后,我想跳过5行并打印下一行。例如 Lecture <==(I want to match lecture) 1 2 3 4 5 Hello <==(And then i want to print this line) 我做错了什么?您可以使用该变量跟踪匹配发生的行号,并跳过所需的行号。说: perl -ne '/^Lecture/ && do {$l=$.} ; $.==$l+6 && print
Lecture <==(I want to match lecture)
1
2
3
4
5
Hello <==(And then i want to print this line)
我做错了什么?您可以使用该变量跟踪匹配发生的行号,并跳过所需的行号。说:
perl -ne '/^Lecture/ && do {$l=$.} ; $.==$l+6 && print' inputfile
将在匹配后打印第6行(在本例中,生成Hello
)。\usr/bin/perl
严格使用;
使用警告;
打开我的$fh,“perl-ne”$l=$。如果/^讲座/;如果美元=$l+6'文件
if($line=~m/(讲座)/){$1=$currentLine;if($currentLine==$1+6){print$currentLine;}}我试过这么做,但没用。是否存在任何问题?请使用除$1
以外的变量名,其值将在每次迭代时替换为讲座
(由于正则表达式中存在(不必要的)捕获组)。此外,内部if
应位于外部。
perl -ne '/^Lecture/ && do {$l=$.} ; $.==$l+6 && print' inputfile
#/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
}
}