Have you ever found yourself needing to quickly sort IP addresses directly from the Linux shell? You just ran grep against all of your configs looking for IPs in some subnet, but they're all unordered, and you just wish you could pipe the output and have them sorted.

I kept running into the same problem. When it got painful enough I found a website that allowed me to copy-paste and sort all of the IPs. That worked for a while but wasn't satisfying enough. Then I found a cool looking bash one-liner, with cut, sort, and other unix utilities, combined together to deliver the goods. This was much better, I could work with it directly from the shell and it did the job.

But then, one day, I thought, hey, let's reinvent the wheel using Python, because why not, and it's going to be fun! So that's what I did. I wrote a Python script, added it to my /usr/bin/, and now I can pipe, redirect, and call it from wherever I want. It works, and it's mine. Mission accomplished.

Now, I figured, maybe others are going through the same motions, except they don't have time, or don't like reinventing wheel, but still would like to pipe their grep queries and have IPs sorted. So I'm putting my script up on GitHub. If you like, you can take it and have as much fun with it as I do.

Some examples of how it can be used are below.

  • Pipe results of the grep query for sorting:
$ grep "10\.2\." * | ipsorter
  • Sort IP addresses read from a file:
$ ipsorter random_ips.txt
  • Use input redirect:
$ ipsorter < random_ips.txt

Script has a very crude regex check so that lines not containing IP addresses are ignored. This comes especially handy when results of our grep have things other than just IP addresses in them.

That's it, if you're interested, head over to my GitHub repo, link below, and help yourself to the mighty 'ipsorter'!