Linux

Sort Host File - Perl

Sorting

Recentrly I had to sort more than 100 thousand host names alphabetically. The tricky part was that these were domains, and I wanted to sort them by top level domain.

The following perl script can do that. Just paste all the host names inside the script file as shown in the section below:

my @hosts = (

  'zzztech.com',
  'www.zzztech.com',
  'zzzzzz.com',
  'www.zzzzzz.com',

);

The Script

use feature qw( say state );
use Domain::PublicSuffix qw( );

sub get_sort_key {
  my ($host) = @_;
  $host =~ s/\.\z//;
  state $dps = Domain::PublicSuffix->new();
  $dps->get_root_domain($host)
  or die "$host: ".$dps->error();

  my @name= split /\./, substr($host, 0, -length($dps->suffix())-1);
  my @suffix = split /\./, $dps->suffix();
return join '.', reverse @suffix, @name;
}

my @hosts = (

  'zzztech.com',
  'www.zzztech.com',
  'zzzzzz.com',
  'www.zzzzzz.com',

);

my @sorted_hosts =
map s/^[^\0]*\0//r,
sort
map get_sort_key($_)."\0".$_,
@hosts;

say for @sorted_hosts;