Sort Hosts File With Perl
Recently I had to sort more than 100 thousand hosts alphabetically. The tricky part was that these were domains, and I wanted to sort them by top-level domain. Before you can use the script you need to install Domain::PublicSuffix.
The following perl script can do that. Just paste all the host names inside the script file as shown in the example below:
my @hosts = (
'zzztech.com',
'www.zzztech.com',
'zzzzzz.com',
'www.zzzzzz.com',
);
sort_hosts.pl
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;
Execute it with:
perl sort_hosts.pl
The sorted results will be displayed in the tty. To pipe to a new file type:
perl sort_hosts.pl > My_Sorted_Hosts.txt
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}