Unix - count unique IP addresses, sort them by most frequent and also sort them by IP when number of repetitions is same

5,856

If your sort can do a stable sort, e.g. GNU sort with the -s or --stable option, lines with fields unrelated to the sort keys will not be sorted by those fields when there are ties, but will stay in their same relative positions.

$ sort -n -t. -k1,1 -k2,2 -k3,3 -k4,4 | uniq -c | sort -n -r -s
  5 72.204.55.250
  2 96.41.51.202
  2 141.8.143.179
  2 178.137.94.166
  2 208.115.113.91
Share:
5,856

Related videos on Youtube

Lkopo
Author by

Lkopo

Updated on September 18, 2022

Comments

  • Lkopo
    Lkopo almost 2 years

    I have a list of IP addresses in file:

      72.204.55.250
      72.204.55.250
      72.204.55.250
      72.204.55.250
      72.204.55.250
      96.41.51.202
      208.115.113.91
      178.137.94.166
      178.137.94.166
      208.115.113.91
      96.41.51.202
      141.8.143.179
      141.8.143.179
    

    Now I am going to sort them and call uniq -c service and I get:

      2  141.8.143.179
      2  178.137.94.166
      2  208.115.113.91
      5  72.204.55.250
      2  96.41.51.202
    

    Now I will sort them by most frequent (sort -rn) but my problem is to also sort them by IP address when the number of repetitions is same in descending order. I've found a sort command for only IP address which works:

    sort -rn -t . -k1,1 -k2,2 -k 3,3 -k4,4
    

    but as I mentioned it above, I don't know how to combine it with first column (number of repetitions) to get these expected results:

      5  72.204.55.250
      2  208.115.113.91
      2  178.137.94.166
      2  141.8.143.179
      2  96.41.51.202
    

    How can I achieve that? Thanks in advance for any help.

    • cutrightjm
      cutrightjm over 8 years
      Well you can use this to get the quantity sorted in the correct order, but the ip addresses themselves will be in reverse order: sort -rn <file> | uniq -c
    • Lkopo
      Lkopo over 8 years
      Exactly and there is the problem - I need them both in the same order.
  • Lkopo
    Lkopo over 8 years
    @don_crissti yes it is needed, some IP addresses are not sorted correctly. This is a correct answer for me, just when you want to sort IP addresses in descending order too, just add -r in first sort. Thank you so much!