Que tal
tr -d [:blank:] < hosts | # remove trailing whitespace
perl -lne 'print join ".", reverse(split /\./)' | # reverse order of fields
sort | # sort
awk -F. '
!seen[$1.$2.$3]++ && NR>1 {print ""} # insert blank line when tld,dom,sub change
{for (i=NF;i>1;i--) printf "%s.", $i; print $1} # print fields in original order
'
dando
bar.foo.com
foofoo.bar.foo.com
morefoo.bar.foo.com
fufu.isub1.foo.com
sub1.foo.com
fufu.sub1.foo.com
morefu.sub1.foo.com
www.foo.com
Melhor (espero) a implementação do mesmo algoritmo, usando um hash de hashes perl:
#!/usr/bin/perl
use strict;
use warnings;
my %domains = ();
while (defined($_ = <ARGV>)) {
chomp $_ ;
$_ =~ s/\s+//;
my @F = reverse(split(/\./));
my $domain = join(".", @F[0..2]);
if ( ! exists($domains{$domain}) ) {
$domains{$domain} = {};
}
$domains{$domain}{join(".", @F)}++;
}
foreach my $domain (sort keys %domains) {
foreach my $host (sort keys %{ $domains{$domain} }) {
print join(".", reverse(split(/\./, $host))), "\n";
}
print "\n"
}