user1720205
user1720205

Reputation:

Getting word count with Grep

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

Upvotes: 1

Views: 496

Answers (2)

Daniel Frey
Daniel Frey

Reputation: 56863

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.

Upvotes: 5

Kent
Kent

Reputation: 195049

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

Upvotes: 0

Related Questions