100より大きい数字を持つ行の数を数える

100より大きい数字を持つ行の数を数える

たくさんの数字 (数字のみで、各数字が 1 行に入っています) が入ったファイルがあります。数字が 100 (または実際は他の数字) より大きい行の数を調べたいのですが、どうすればよいですか?

答え1

次のテスト ファイルを検討してみましょう。

$ cat myfile
98
99
100
101
102
103
104
105

ここで、100 より大きい数字の行の数を数えてみましょう。

$ awk '$1>100{c++} END{print c+0}' myfile
5

使い方

  • $1>100{c++}

    行の数字が 100 を超えるたびに、変数はc1 ずつ増加します。

  • END{print c+0}

    ファイルの読み取りが完了すると、変数cが印刷されます。

    0を追加することで、awk は を数値としてc扱うようになります。 数値 を含む行があった場合、 はすでに数値です。 行がなかった場合、 は空になります (ヒント:c>100ccイルヴァル)。これにゼロを追加することで、空の文字列が に変更され0、より正確な出力が得られます。

答え2

同様の解決策perl

$ seq 98 105 | perl -ne '$c++ if $_ > 100; END{print $c+0 ."\n"}'
5


速度比較:3回連続で報告された数値

ランダムファイル:

$ perl -le 'print int(rand(200)) foreach (0..10000000)' > rand_numbers.txt
$ perl -le 'print int(rand(100200)) foreach (0..10000000)' >> rand_numbers.txt

$ shuf rand_numbers.txt -o rand_numbers.txt 
$ tail -5 rand_numbers.txt 
114
100
66125
84281
144
$ wc rand_numbers.txt 
20000002 20000002 93413515 rand_numbers.txt
$ du -h rand_numbers.txt 
90M rand_numbers.txt

awk

$ time awk '$1>100{c++} END{print c+0}' rand_numbers.txt 
14940305

real    0m7.754s
real    0m8.150s
real    0m7.439s

perl

$ time perl -ne '$c++ if $_ > 100; END{print $c+0 ."\n"}' rand_numbers.txt 
14940305

real    0m4.145s
real    0m4.146s
real    0m4.196s

そしてただ楽しみのためにgrep更新しました: LC_ALL=C の Perl よりも高速です)

$ time grep -xcE '10[1-9]|1[1-9][0-9]|[2-9][0-9]{2,}|1[0-9]{3,}' rand_numbers.txt 
14940305

real    0m10.622s

$ time LC_ALL=C grep -xcE '10[1-9]|1[1-9][0-9]|[2-9][0-9]{2,}|1[0-9]{3,}' rand_numbers.txt
14940305

real    0m0.886s
real    0m0.889s
real    0m0.892s

sed面白くない:

$ time sed -nE '/^10[1-9]|1[1-9][0-9]|[2-9][0-9]{2,}|1[0-9]{3,}$/p' rand_numbers.txt | wc -l
14940305

real    0m11.929s

$ time LC_ALL=C sed -nE '/^10[1-9]|1[1-9][0-9]|[2-9][0-9]{2,}|1[0-9]{3,}$/p' rand_numbers.txt | wc -l
14940305

real    0m6.238s

関連情報