perl行计数包含特定文本的文件

时间:2013-07-17 07:26:28

标签: perl parameters line-count

基本上我想计算包含单词Out的行的数字。

my $lc1 = 0;
open my $file, "<", "LNP_Define.cfg" or die($!);
#return [ grep m|Out|, <$file> ]; (I tried something with return to but also failed)
#$lc1++ while <$file>;
#while <$file> {$lc1++ if (the idea of the if statement is to count lines if it contains  Out)
close $file;
print $lc1, "\n";

2 个答案:

答案 0 :(得分:1)

命令行也可能是你的潜在选择:

perl -ne '$lc1++ if /Out/; END { print "$lc1\n"; } ' LNP_Define.cfg

-n 假设结束之前所有代码的循环。
-e 期望代码被''包围。

仅当以下if语句为真时, $ lc1 ++ 才会计算。

每行都会运行 if 语句,以查找“ Out ”。

END {} 语句用于while循环结束后的处理。您可以在这里打印计数。

或没有命令行:

my $lc1;
while ( readline ) {
    $lc1++ if /Out/; 
}    
print "$lc1\n";

然后在命令行上运行:

$ perl count.pl LNP_Define.cfg

答案 1 :(得分:0)

使用index

0 <= index $_, 'Out' and $lc1++ while <$file>;
相关问题