I have a list with 1601 lines, where on each line, I am interested in counting the # of times different values appear for fields 5.

Here's what I have so far:

awk '{print$5}' FILE  | sort | uniq -c

What this gives me is a list of uniq values, with their respective counts. But I would like to sort this list. I've been seeing answers that discuss keys and values, but it hasn't been clear how I can apply it to my case.

Thank you for any help in advance.


You're just missing a sort -b -n at the end of the pipeline (as another stage of it):

awk '{ print $5 }' FILE  | sort | uniq -c | sort -b -n

sort -b -n will sort the lines produced by the earlier stages of the pipeline numerically (ignoring leading blanks). If two lines has the same number at the start, a lexicographical ordering of the lines will be performed.

  • what's the way to get it in descending? This gives ascending. Tx!
    – ZakS
    Jul 16 '19 at 13:16
  • Ah - just add -r
    – ZakS
    Jul 16 '19 at 13:18

Just sort again by column. Using -k1 sorts by the first column (occurrences), using -k2 sorts by the second column (values):

awk '{print $5}' FILE | sort | uniq -c | sort -k1   # Sort by ascending occurrences
awk '{print $5}' FILE | sort | uniq -c | sort -k2   # Sort by ascending values

If you need it in descending order (-r):

awk '{print $5}' FILE | sort | uniq -c | sort -k1 -r   # Sort by descending occurrences
awk '{print $5}' FILE | sort | uniq -c | sort -k2 -r   # Sort by descending values
  • You need to specify a numeric sort to sort numbers correctly.
    – Kusalananda
    Jul 16 '19 at 10:00
  • Why? I tried it without -n and numbers are sorted correctly: paste.ofcode.org/33G3SYVgczZu6eC453tAH4h. This is my sort version: sort (GNU coreutils) 8.26
    – ordago
    Jul 16 '19 at 10:45
  • Ah, I see now. uniq -c outputs the numbers preceded by spaces, which is why it works.
    – Kusalananda
    Jul 16 '19 at 10:57
  • the final sort -k1 gave me a weird result. The order of the occurrences was 10, 1, 118, 1, 13,16,1, 23... any idea why? I get the feeling it doesn't look at it like a numeric value but don't understand why the 1's don't appear together. Full command line was: awk '{print$5}' FILE | | sort | uniq -c | sort -k2
    – ZakS
    Jul 16 '19 at 13:18

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.