【问题标题】:Output the line numbers where a string appears输出出现字符串的行号
【发布时间】: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}'

标签: file perl text


【解决方案1】:

您的代码存在许多问题,但是错误打印行号的原因是每次Apples 出现在一行上时您将变量$counter 递增一次并将其保存到@lineAry .这与字符串出现的行号不同,最简单的解决方法是使用内置变量$.,它表示对文件句柄执行读取的次数

另外,我鼓励你使用词法文件句柄和open的三参数形式,并检查对open的每次调用是否成功

你从不使用$initialLine的值,我不明白你为什么把它初始化为10

我会这样写

use strict;
use warnings 'all';

my $filename = 'file.txt';

open my $fh, '<', $filename or die qq{Unable to open "$filename" for input: $!};

my @lines;
my $n;

while ( <$fh> ) {
    push @lines, $. if /apples/i;
    ++$n while /apples/ig;
}

print "Apples appear $n times in this file\n";
print "Apples appear on these lines: ", join( ', ', @lines ), "\n\n";

输出

Apples appear 2 times in this file
Apples appear on these lines: 1, 4

【讨论】:

  • my $n = 0; 没有苹果的时候。
  • @Kjetil:同意,但我更希望看到警告,因为 on these lines 也需要修复,而且对于这种情况来说不值得。
  • 我明白你的意思,if $n&gt;0 可以附加到最后一行。
【解决方案2】:

改变

push(@lineAry, $counter);

push(@lineAry, $.);

$.是使用perl的while (&lt;&gt;)时存储行号的变量。

如果您想使用 $counter 变量,另一种方法是在每一行而不是每场比赛上移动增量。

【讨论】:

    猜你喜欢
    • 2015-12-22
    • 1970-01-01
    • 2022-01-08
    • 2019-04-08
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 2022-01-24
    • 2022-06-13
    相关资源
    最近更新 更多