wc -l vs. grep -c


0. Contents

1.Concept
2.Test Script
3.Run Test
4.Summary


1. Concept

コマンドラインにおいてファイルの行数を調べるには
wc -l が便利だが、行数のみを変数に代入するには一工夫必要になる。
grep -c でもファイルの行数を数える事ができるので
シェルスクリプトで扱う場合の最適な方法を探ってみる。


2. Test Script

100行の行番号だけが書かれたファイルを用意して
比較の為のスクリプトを作成した。
ソースは以下の通り。

Script1
#! /usr/bin/env bash
seq 1 100 > test.txt

a=$( wc -l test.txt )
b=$( cat test.txt | wc -l )
c=$( wc -l < test.txt )
d=$( grep -c '' test.txt )

echo "'a:$a'"
echo "'b:$b'"
echo "'c:$c'"
echo "'d:$d'"
exit

Script2
#! /usr/bin/env bash
seq 1 100 > test.txt

test1(){
  for (( i=1; i <= 100; i++ )) ; do
    a=$( cat test.txt | wc -l )
  done
}

test2(){
  for (( i=1; i <= 100; i++ )) ; do
    a=$( grep -c '' test.txt )
  done
}

test3(){
  for (( i=1; i <= 100; i++ )) ; do
    a=$( wc -l < test.txt )
  done
}

time test1
time test2
time test3
exit


3. Run Test

上記のスクリプトの実行結果。

Script1
'a:    100 test.txt'
'b:    100'
'c:100'
'd:100'

Script2
test1: cat test.txt | wc -l
real    0m9.976s
user    0m1.075s
sys     0m0.531s

test2: grep -c '' test.txt
real    0m4.180s
user    0m1.297s
sys     0m0.536s

test3: wc -l < test.txt
real    0m4.524s
user    0m0.984s
sys     0m0.378s


4. Summary

処理速度を重視するなら grep -c '' file、
文字数や分かりやすさを重視するなら wc -l < file を
使うのがお勧めである。