linux – HrĨkov b(r)log http://192.168.1.4:9084 hamster blog Wed, 19 Jan 2022 11:10:38 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.2 Sort uniq IP address from Apache log http://192.168.1.4:9084/sort-uniq-ip-address-from-apache-log/ Mon, 06 Feb 2017 22:14:45 +0000 http://192.168.1.4:9084/?p=3633 Read more]]> I’m trying to extract IP addresses from my apache log, count and sort them.

Using the numeric in the first sort will give you the desired result:

cat access.log | awk '{print $1}' | sort -n | uniq -c | sort -nr | head -20

15 212.XXX.XXX.XXX
2 198.XXX.XXX.XXX
1 216.XXX.XXX.XXX
1 139.XXX.XXX.XXX
10 51.XXX.XXX.XXX
2 37.XXX.XXX.XXX
1 76.XXX.XXX.XXX
1 74.XXX.XXX.XXX
1 51.XXX.XXX.XXX

But sort -n didn’t work, so I added some non numeric character between the counter and the IP address

cat access.log | awk '{ print $1 } ' | sort | uniq -c | sed -r 's/^[ \t]*([0-9]+) (.*)$/\1 --- \2/' | sort -rn

15 --- 212.XXX.XXX.XXX
10 --- 51.XXX.XXX.XXX
2 --- 37.XXX.XXX.XXX
2 --- 198.XXX.XXX.XXX
1 --- 76.XXX.XXX.XXX
1 --- 74.XXX.XXX.XXX
1 --- 51.XXX.XXX.XXX
1 --- 216.XXX.XXX.XXX
1 --- 139.XXX.XXX.XXX

]]>