Linux / UNIX Shell: Sort IP Address

by Vivek Gite [Last updated: September 17, 2008]

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
Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our daily email newsletter to make sure you don't miss a single tip/tricks. Subscribe to our weekly newsletter here!

{ 2 comments… read them below or add one }

1 Vaishnavi 09.17.08 at 10:20 am

A very good example. Your site is amazing and I look forward to your posts all the time :)

2 Raymond 09.17.08 at 3:01 pm

I’ve been follow your site 6 months, faq section is always very informative. keep up your good work..

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Tagged as: , , , , , , , , , , , ,

Previous post: CentOS / Red Hat Linux Install PHP 5.x PECL Filter Extension

Next post: FreeBSD: Cannot load /usr/local/libexec/apache22/mod_security2.so into server: /usr/local/libexec/apache22/mod_security2.so