Recursive File Counts By Directory

I’ve occassionally wanted to know which directory in a tree has the
most files in it, rather than the most space used, which is what
“du” reports.

It’s not a great script, but it works well enough. Example usage:

$ perl /tmp/dircount.pl /etc/ | sort -n | tail
25 /etc//openldap
26 /etc//fonts/conf.avail
33 /etc//pam.d
35 /etc//runlevels
45 /etc//fonts
46 /etc//conf.d
76 /etc//init.d
212 /etc//ssl/certs
228 /etc//ssl
861 /etc/


And here’s the code:

#!env perl

my $indir=$ARGV[0];

if( ! "$indir" || $indir !~ m{^/} )
{
        print "Input must be a single absolute path.\n";
        exit 1;
}

sub dircount {
        my $dir = shift;
        # print "dir: $dir\n";
        my $count = 0;
        opendir( my $dirhandle, $dir );
        foreach my $file (readdir( $dirhandle )) {
                next if( $file =~ m{^..?$} );
                my $new = "$dir/$file";
                $new =~ s{/+}{/}g;
                $count += 1;
                if( -d $new && ! -l $new )
                {
                        $count += dircount( $new );
                }
        }
        print "$count $dir\n";
        return $count;
}

dircount($indir);