-4

I want to sort a set of IPv6 addresses based on the nth column of the address.

Specifically they're stored in a file. If I have a file with these lines...

5128581|::|2001:4:ffff:ffff:ffff:ffff:ffff:ffff||1

2747125|2001:6::|2001:5:0:ffff:ffff:ffff:ffff:ffff||2

745044|2001:5:1::|2001:5:1:ffff:ffff:ffff:ffff:ffff||3

I'd like to sort them by the 2nd column to get the following output:

5128581|::|2001:4:ffff:ffff:ffff:ffff:ffff:ffff||1

745044|2001:5:1::|2001:5:1:ffff:ffff:ffff:ffff:ffff||3

2747125|2001:6::|2001:5:0:ffff:ffff:ffff:ffff:ffff||2

How can I do that?

I've found some useful questions about this (Sort a file by first (or second, or else) column in python, Sorting IP Addresses in a Python Script) but I can't figure this out.

doppelgreener
  • 4,809
  • 10
  • 46
  • 63
Vikash Kumar
  • 31
  • 11

1 Answers1

2

For parsing IPv6 address you could use ipaddress module. For sorting by n-th column you can use key parameter in sorted() function. This should give you an idea:

import ipaddress
from pprint import pprint

i = [('c1', 'b2', '2::'), 
     ('a1', 'c2', '1::'),
     ('b1', 'a2', '3::')]

out = sorted(i, key=lambda v: ipaddress.ip_address(v[2])) # sort by column 2 (0-indexed)
pprint(out, width=25)

Output:

[('a1', 'c2', '1::'),
 ('c1', 'b2', '2::'),
 ('b1', 'a2', '3::')]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91