[uniq] -c で重複行の出現回数をカウントする
作成日: 2026年10月10日
uniq コマンドの -c オプションを使用すると、連続する重複行をまとめて、それぞれの行の出現回数を先頭に付けて表示できます。
例えば、次のコマンドを実行します。
printf '%s\n' apple banana apple banana banana orange | sort | uniq -c
GNU Coreutils 9.7 での実行結果は次のとおりです。
2 apple
3 banana
1 orange
数字の前の空白は桁を揃えるためのもので、uniq の実装によって空白の数が異なる場合があります。
-c(または --count)は各行の出現回数を数えて行頭に出力するオプションです。
uniq は隣接する連続した行だけを比較するため、ファイル全体で重複を集計する場合は、事前に sort コマンドで並べ替えておく必要があります。
出現回数の多い順に並べ替えたい場合は、次のように sort -nr と組み合わせます。
printf '%s\n' apple banana apple banana banana orange | sort | uniq -c | sort -nr
GNU Coreutils 9.7 での実行結果は次のとおりです。
3 banana
2 apple
1 orange
参考
- GNU Coreutils - uniq invocation: https://www.gnu.org/software/coreutils/manual/html_node/uniq-invocation.html