Sorting IP Addresses via bash

Sort list of IP addresses via command line

Do you have a text file filled with a bunch of IP addresses, and it won’t sort properly with the -n option alone? Providing additional options can help achive the desired output.

$ cat nfs_clients | sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4

A description of the additional options from the sort man page:

-k, --key=POS1[,POS2]
start a key at POS1 (origin 1), end it at POS2 (default end of line)

-t, --field-separator=SEP
use SEP instead of non-blank to blank transition

From the command line example above, we’ve indicated the ‘dot’ or ‘period’ to be the field-separator and have defined keys in each of the IPs octets.