【发布时间】:2019-02-18 05:04:37
【问题描述】:
我正在尝试确定字符串Apples 在文本文件中出现的次数以及出现在哪些行中。
脚本输出不正确的行号,而是连续输出数字(1,2,..),而不是单词的正确行。
文件.txt
Apples
Grapes
Oranges
Apples
目标输出
Apples appear 2 times in this file
Apples appear on these lines: 1, 4,
相反,我的输出如下代码所示:
Apples appear 2 times in this file
Apples appear on these lines: 1, 2,
Perl
my $filename = "<file.txt";
open( TEXT, $filename );
$initialLine = 10; ## holds the number of the line
$line = 0;
$counter = 0;
# holder for line numbers
@lineAry = ();
while ( $line = <TEXT> ) {
chomp( $line );
if ( $line =~ /Apples/ ) {
while ( $line =~ /Apples/ig ) {
$counter++;
}
push( @lineAry, $counter );
$initialLine++;
}
}
close( TEXT );
# print "\n\n'Apples' occurs $counter times in file.\n";
print "Apples appear $counter times in this file\n";
print "Apples appear on these lines: ";
foreach $a ( @lineAry ) {
print "$a, ";
}
print "\n\n";
exit;
【问题讨论】:
-
$ grep -nr 苹果文件1 | awk '{count++;print $0}END{print count}'