A perl script to find large directories in a given folder

Sep 14, '07 07:30:00AM

Contributed by: coppit

Here's a little perl script that can be used to find the top ten largest directories from the argument directories. To use it, save it as dirsize in your user's .bin folder (and make it executable with chmod a+x dirsize), modify your .bashrc to add ~/bin to your path, then run something like this in Terminal: dirsize ~/*. Here's the code:

#!/usr/bin/perl
use strict;
die "usage: $0 <directories>\n" unless @ARGV;
@ARGV = map { "'$_'" } @ARGV;
my @results = `du -hs @ARGV`;
@results = sort human_sort @results;
@results = @results[0..9];
print @results;

#---------------------------------------------------------------------------
sub human_sort {
	my ($size_a) = $a =~ /^(\S+)/;
	my ($size_b) = $b =~ /^(\S+)/;

	$size_a = $1 * 1024 if $size_a =~ /^(.*)k$/;
	$size_a = $1 * 1024 * 1024 if $size_a =~ /^(.*)M$/;
	$size_a = $1 * 1024 * 1024 * 1024 if $size_a =~ /^(.*)G$/;

	$size_b = $1 * 1024 if $size_b =~ /^(.*)k$/;
	$size_b = $1 * 1024 * 1024 if $size_b =~ /^(.*)M$/;
	$size_b = $1 * 1024 * 1024 * 1024 if $size_b =~ /^(.*)G$/;

	return $size_b <=> $size_a;
}

[robg adds: I tested this, and it seems to work as expected -- it will take a while to run if you set it to work on a large tree structure.]

Comments (9)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20070912091217207