Python - ファイルの中にある特定文字列を数える - Qiita
触発されて。
- pythonみたいにcountメソッドは無いのでsplitで代用。
- splitは分割数なので-1する。(マッチしない行でも1個の分割数)
- splitでなくて正規表現の置換した数でもできそうだが、遅そう。
- エラー処理は面倒だったので省略。
- ファイルを丸呑みできるなら
match_count.pl
#!/usr/bin/perl
use strict;
use warnings;
sub count_words
{
my ($stream, $search_word) = @_;
my $num = 0;
while (<$stream>) {
my $match_num = scalar (my @list = split /$search_word/, $_) - 1;
$num += $match_num;
}
return $num;
}
sub main
{
if (-t) {
my ($file, $search_word) = @ARGV;
open my $fh, "<", $file;
print count_words($fh, $search_word) . "\n";
close $fh;
}
else {
my $stdin = "STDIN";
my ($search_word) = @ARGV;
print count_words($stdin, $search_word) . "\n";
}
}
if ($0 eq __FILE__) {
main();
}
hoge.txt
hogefugapiyohogefugapiyo
hogehogehogehogehogehoge
$ chmod +x match_count.pl
$ ./match_count.pl hoge.txt hoge
8
$ cat hoge.txt | ./match_count.pl hoge
8