Question

I have been using

grep -o string file | wc -l

to obtain word counts, but I have a file of the format

help
help
help
how
how
luke
mark

And I was wondering if there was a command that would return: 3,2,1,1

Instead of running the previous command multiple times

Was it helpful?

Solution

You can use

sort input.txt | uniq -c

which will output

   3 help
   2 how
   1 luke
   1 mark

from which you could continue processing the output. If you already know that the same entries are in a continuous block of lines you could of course skip the sort and use uniq directly, which will also preserve the order.

OTHER TIPS

single process awk way

awk '{a[$0]++}END{for(x in a)print x" : "a[x]}' file

kent$  echo "help
help
help
how
how
luke
mark"|awk '{a[$0]++}END{for(x in a)print x" : "a[x]}'
luke : 1
help : 3
how : 2
mark : 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top