[英]perl line count a file containing a specific text
Basically I want to count the number if lines which contain the word Out. 基本上,我想计算包含单词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";
The command line might be potential option for you too: 命令行也可能是您的潜在选择:
perl -ne '$lc1++ if /Out/; END { print "$lc1\n"; } ' LNP_Define.cfg
The -n assumes a while loop for all your code before END . -n为END之前的所有代码假定一个while循环。
The -e expects code surrounded by ' ' . -e期望代码被''包围。
The $lc1++ will count only if the following if statement is true. 仅当以下if语句为true时, $ lc1 ++才计数。
The if statement runs per line looking for " Out ". if语句每行运行一次,以查找“ Out ”。
The END { } statement is for processing after the while loops ends. END {}语句用于在while循环结束后进行处理。 Here is where you can print the count.
您可以在此处打印计数。
Or without the command line: 或不带命令行:
my $lc1;
while ( readline ) {
$lc1++ if /Out/;
}
print "$lc1\n";
Then run on the command line: 然后在命令行上运行:
$ perl count.pl LNP_Define.cfg
使用index
:
0 <= index $_, 'Out' and $lc1++ while <$file>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.