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

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

-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

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
comments powered by Disqus