Sorting IP Addresses

Sort a list of IPv4 addresses numerically by treating each octet as a separate sort key:

sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n file.txt

How it works:

  • -t . — use . as the field separator (splitting the IP into octets)
  • -k 1,1n — sort by the first octet, numerically
  • -k 2,2n — then by the second octet, numerically
  • and so on for octets 3 and 4

Example:

$ cat ips.txt
10.1.3.2
254.1.3.2
192.168.37.254
192.168.37.16

$ sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n ips.txt
10.1.3.2
192.168.37.16
192.168.37.254
254.1.3.2

Without the numeric flag (n), sort would compare octets lexicographically (e.g., 16 before 2), giving incorrect ordering.

  • nmap — scan output often produces IP lists that need sorting
  • grep — filter before sorting

Sources