3

I have an unsorted list of IPs that I need to count and sort by occurrences.
I use sort -n | uniq -c | sort -n and that works well, but I'd like something less expensive... surely awk can do this?

Input

1.1.1.1
2.2.2.2
1.1.1.1
3.3.3.3
2.2.2.2
1.1.1.1

Output

3 1.1.1.1
2 2.2.2.2
1 3.3.3.3
  • 1
    post some input fragment and expected result – RomanPerekhrest Oct 29 '17 at 21:31
  • 4
    This is likely to be less expensive than the awk accumulator solution unless there is a huge proportion of duplicates. – Gilles Oct 29 '17 at 21:50
8

With single awk process:

awk '{ a[$1]++ }END{ for(i in a) print a[i],i }' file

The output:

3 1.1.1.1
2 2.2.2.2
1 3.3.3.3

To output records sorted by number of occurrences in descending order use the following GNU awk approach:

awk 'BEGIN{ PROCINFO["sorted_in"]="@val_num_desc" }{ a[$1]++ }
     END{ for(i in a) print a[i],i }' file
  • 1
    that won't do the final sort by the number of hits, but just gives the output in the order awk happens to give the keys – ilkkachu Oct 29 '17 at 22:43
  • 1
    @ilkkachu, see my update – RomanPerekhrest Oct 29 '17 at 22:51

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.