我想对一个单词进行两次准确的匹配。输出不应显示所有匹配项。如何使用perl?
open(a,"<file.txt");
open(c,">>output.txt");
while (my $line = <a>) {
if($line =~ m/know{2}/) {
print $line;
}
}
close(a);
close(c);
示例: 如果file.txt有以下几行:
I know Perl.
I know English.
I know French.
I know Dutch.
预期结果应为:
I know Perl.
I know English.
答案 0 :(得分:2)
您似乎在询问如何查找包含know
的前两行。
为此,您需要跟踪先前找到的行数。
my $count = 0;
while (<>) {
if (/know/) {
print;
last if ++$count == 2;
}
}
答案 1 :(得分:1)
尝试使用此Perl单线版
$ perl -ne 'BEGIN {$x=2} s/(know)/$x--;$kv{$_}=1/ge; if($x==0) { print keys %kv ; exit } ' cherry2.txt
I know Perl.
I know English.
$
$ cat cherry2.txt
I know Perl.
I know English.
I know French.
I know Dutch.
$