やーまんぶろぐ

気が向いた時にだけ書くブログ

ワンライナー 文字列マッチする行をカウントする方法

文字列マッチする行をカウントする方法をいくつかメモしておきます。

以下の内容が書かれたtestファイルからcountという文字列にマッチする行をカウントするという例で書いています。

$ cat test
count1
count2
count3

単純にgrepして目で数える場合

(なんかのコマンド) | grep (期待する文字列)
ex)
$ cat test | grep count
count1
count2
count3

マッチする行数だけ知りたい場合

(なんかのコマンド) | grep (期待する文字列) | wc -l
ex)
$ cat test | grep count | wc -l
3

カウント数が期待通りかを戻り値で判定したい場合

(なんかのコマンド) | grep (期待する文字列) | wc -l | grep -w (期待している数)
ex)
$ cat test | grep count | wc -l | grep -w 3
3
$ echo $?
0

カウント数が期待通りかを戻り値で判定しつつ、出力を表示したい場合

(なんかのコマンド) | grep (期待する文字列) | tee /dev/stderr | wc -l | grep -w (期待している数)
ex)
$ cat test | grep count | tee /dev/stderr | wc -l | grep -w 3
count1
count2
count3
3
$ echo?
0

おまけ カウントは判定に使うだけで表示させたくない場合

(なんかのコマンド) | grep count | tee /dev/stderr | wc -l | grep -w 3 > /dev/null
ex)
$ cat test | grep count | tee /dev/stderr | wc -l | grep -w 3 > /dev/null
count1
count2
count3
$ echo?
0