Bhabani Shankar Bhabani Shankar - 7 months ago 28
Bash Question

count the number of occurrences of all word in unix

I have a file like below:

abc
mnm
xyz
abc
abc
xyz


Now I want to know the count of each word in the file with a single command in UNIX. Is that possible

Answer

Well it takes two programs but it's just one statement:

sort filename.txt | uniq -c

You could also write a shell function:

counts() {
     sort "$@" | uniq -c
}

Then you can simply say:

counts filename.txt