Q. I'd like to sort a list of IP address stored in a text file. How do I sort by last notation or entire address under Linux or UNIX operating systems?
A.. You need to use sort command to displays the lines of its input listed in sorted order. Sorting is done based on one or more sort keys extracted from each line of input. By default, the entire input is taken as sort key. Blank space is taken used as default field separator.
Sort command to sort IP address
Here is our sample input file:
192.168.1.100 192.168.1.19 192.168.1.102 192.168.2.1 192.168.0.2
Type the following sort command:
$ sort -t . -k 3,3n -k 4,4n /path/to/file
Sample output:
192.168.0.2 192.168.1.19 192.168.1.100 192.168.1.102 192.168.2.1
Where,
- -t . : Set field to . (dot) as our IPs separated by dot symbol
- -n : Makes the program sort according to numerical value
- -k opts: Sort data / fields using the given column number. For example, the option -k 2 made the program sort using the second column of data. The option -k 3,3n -k 4,4n sorts each column. First it will sort 3rd column and then 4th column.
Further readings:
- man sort
Featured Articles:
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- My 10 UNIX Command Line Mistakes
- 10 Greatest Open Source Software Of 2009
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- Top 20 OpenSSH Server Best Security Practices
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Linux Video Editor Software
- Email FAQ to a friend
- Download PDF version
- Printable version
- Comment RSS feed
- Last Updated: 09/17/08



{ 4 comments… read them below or add one }
A very good example. Your site is amazing and I look forward to your posts all the time :)
I’ve been follow your site 6 months, faq section is always very informative. keep up your good work..
You allude to sorting all columns in an IP address, but don’t specifically state how to.
Here’s the sort command to sort all IP addresses:
sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n /path/to/file
Also, since i’m here, i wanted then to reverse my IP addresses so i could build a reverse zone file for DNS. I found an easy way:
IP=10.120.19.18
IP=(${IP//./ })
Rev=${IP[3]}.${IP[2]}.${IP[1]}.${IP[0]}
echo $Rev
Thanks to you and your sort command for getting me started.
This was really useful. Thanks for the help.