LoginSignup
2
2

More than 5 years have passed since last update.

ランダムに出てくる単語を数え上げるシェルスクリプト

Last updated at Posted at 2017-01-30

やること

words.txt
abc
abc
123
xyz
123
xyz
abc
123
abc

こんなファイルがあったとします。1行に1個「単語」が書かれていて、ファイル内にどんな単語があるのか予めわかってはいません。

で、このファイルを見て
123 -> 3個
abc -> 4個
xyz -> 2個
というふうに、出てきた単語全てについて何個出てきたかを数えたいのです。

やってみたら以外と簡単だった(ノ´ー`)ノ

counter.sh
#!/bin/sh
cat words.txt | sort | uniq | while read WORD
do
  echo "${WORD} "$(grep -c "${WORD}" words.txt)
done

こんな感じでした。

[]$ ./counter.sh 
123 3
abc 4
xyz 2
2
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2