How to Sort IP Addresses in Bash in One Line

by: George El., January 2019, Reading time: 1 minute

Lets assume we have the following file with IPs and we want to sort them. Obviosuly if we sort them like strings, we won’t get what we want. We want to sort on the first octet, then the second, then the third, then the fourth.

more IPs.txt
255.1.1.1
1.1.1.1
120.10.1.5
120.1.1.5
120.1.1.2
12.30.10.10
12.30.10.1
100.10.0.1
100.9.1.9
10.9.0.11
10.9.1.10
1.1.1.1

the command we will use is sort but with a few parameters

$  sort -t . -g -k1,1 -k2,2 -k3,3 -k4,4 IPs.txt
1.1.1.1
1.1.1.1
10.9.0.11
10.9.1.10
12.30.10.1
12.30.10.10
100.9.1.9
100.10.0.1
120.1.1.2
120.1.1.5
120.10.1.5
255.1.1.1

-t specifies the separator to be .
-g treats columns as numerical values
-k1,1 specifies the first column only
-k2,2 specifies the second column only and so on

if we want to see only the unique addresses we pipe the output to uniq function

$  sort -t . -g -k1,1 -k2,2 -k3,3 -k4,4 IPs.txt | uniq
1.1.1.1
10.9.0.11
10.9.1.10
12.30.10.1
12.30.10.10
100.9.1.9
100.10.0.1
120.1.1.2
120.1.1.5
120.10.1.5
255.1.1.1

and if we want to count the number of IP addresses we pipe it to wc -l

$  sort -t . -g -k1,1 -k2,2 -k3,3 -k4,4 IPs.txt | uniq | wc -l
11
comments powered by Disqus