2

Say I have a list such as this:

8
382.34.6
sally
sally
8
923
183.3.3
183.3.3
183.3.3
8

And I want to tally up the number of times each unique value repeats and get output like this:

8 3
382.34.6 1
sally 2
923 1
183.3.3 3

What command would I need to run to do this? If it makes a difference, the list is coming from a grep search.

6

Try this:

sort file | uniq -c | awk '{print $2,$1}'

Output:

183.3.3 3
382.34.6 1
8 3
923 1
sally 2
| improve this answer | |
  • As I saw later, waltinator had a very similar idea. – Cyrus May 31 '15 at 6:34
  • 1
    You can accept @Cyrus's post as the answer if this indeed helped you. – Ron May 31 '15 at 6:59
  • If you prefer to have the counts separated by TAB instead of space (useful if the lines themselves contain space characters), you can use sort file | uniq -c | sed "s%^ *([0-9][0-9]*) %\1\t%g"|awk -F$'\t' {'print $2"\t"$1'} – Ján Lalinský May 31 '15 at 10:17
2

You could feed the list through | sort | uniq -c | sort -n, Like this:

echo -e "8\n382.34.6\nsally\nsally\n8\n923\n183.3.3\n183.3.3\n183.3.3\n8" | \
sort | uniq -c | sort -n
      1 382.34.6
      1 923
      2 sally
      3 183.3.3
      3 8

If you want the counts after the values, you could append | awk '{print $2,$1}'

| improve this answer | |
2

One option is to use awk as follows: create an associative array, keyed by the item to be counted, and increment it each time the same item is read; at the end of input, iterate over the array and print the keys and counts:

your grep command | awk '{a[$0]++;next;}; END{for (i in a) print i,a[i];}'

A possible advantage is that you may be able to do the pattern matching directly in awk, doing away with grep altogether i.e.

awk '/your regex/{a[$0]++;next;}; END{for (i in a) print i,a[i];}'

| improve this answer | |
-1

Try this

stuff=(apple,boat,chicken)
for (i=0; i<${#stuff}; i=i+1); do
echo INPUT | grep ${stuff[i]} | wc
done

INPUT meaning the text to search. Also fill in the array with your words.

| improve this answer | |
  • 1
    -1, sorry but I won't go through all the problems here. It just doesn't work, starting from the fact that you need to enclose a C-style for loop in double parenthesis. Also I'm no bash parameter expansion expert, but your script runs way more than 3 times, and it doesn't output anything but grep errors. Indeed I changed INPUT to "apple test test chicken" while testing. Please revise it, drop me a comment once done and I'll remove my downvote – kos May 31 '15 at 11:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.