I once wrote a script much like the one above. du -b "$@" | sort -n is nice, but du -h is nice too, so I had a shell script for du -b "$@" | perl -pe's/ome/complicated/regex' | sort -n for a while. Recently, I rewrote it in pure Perl.
#!/usr/bin/perl -w
use strict;
use File::Find;
my %conf = (a => 0, c => 0, s => 0, x => 0);
my @dirs = ();
while (defined ($_ = shift)) {
if ($_ eq "--") {push @dirs, @ARGV; last}
elsif (/^-(.*)$/s) {
for (split //, $1) {
if ($_ eq "a" and !$conf{s}) {$conf{a} = 1}
elsif ($_ eq "c") {$conf{c} = 1}
elsif ($_ eq "s" and !$conf{a}) {$conf{s} = 1}
elsif ($_ eq "x") {$conf{x} = 1}
else {
print STDERR "$0 [-a] [-c] [-s] [-x] [--] ...\n";
exit 1;
}
}
}
else {push @dirs, $_}
}
s/\/*$//s for @dirs;
@dirs = qw(.) unless @dirs;
my %spec = (no_chdir => 1);
if ($conf{a}) {
$spec{wanted} = sub {
stat;
my $s = -f _ ? -s _ : 0;
$File::Find::name =~ /^\Q$dirs[0]\E\/?(.*)$/s;
my @a = split /\//, $1;
for (unshift @a, $dirs[0]; @a; pop @a) {
$_{join "/", @a} += $s;
}
};
}
elsif ($conf{s}) {
$spec{wanted} = sub {
stat;
$_{$dirs[0]} += -f _ ? -s _ : 0;
};
}
else {
$spec{wanted} = sub {
stat;
my $s = -f _ ? -s _ : 0;
$File::Find::name =~ /^\Q$dirs[0]\E\/?(.*)$/s;
my @a = split /\//, $1;
! -d _ and pop @a;
for (unshift @a, $dirs[0]; @a; pop @a) {
$_{join "/", @a} += $s;
}
};
}
if ($conf{x}) {
$spec{preprocess} = sub {
my $dev = (lstat $File::Find::dir)[0];
grep {$dev == (lstat "$File::Find::dir/$_")[0]} @_;
};
}
while (@dirs) {
find(\%spec, $dirs[0] eq "" ? "/" : $dirs[0]);
$_{""} += $_{$dirs[0]} if $conf{c};
shift @dirs;
}
$_{$_} < 1024 ** 1 ? printf "%s «%-6.6sB» %s\n", $_{$_}, sprintf("%6.6
+f", "$_{$_}" / 1024 ** 0), $_ :
$_{$_} < 1024 ** 2 ? printf "%s «%-6.6sK» %s\n", $_{$_}, sprintf("%6.6
+f", "$_{$_}" / 1024 ** 1), $_ :
$_{$_} < 1024 ** 3 ? printf "%s «%-6.6sM» %s\n", $_{$_}, sprintf("%6.6
+f", "$_{$_}" / 1024 ** 2), $_ :
$_{$_} < 1024 ** 4 ? printf "%s «%-6.6sG» %s\n", $_{$_}, sprintf("%6.6
+f", "$_{$_}" / 1024 ** 3), $_ :
$_{$_} < 1024 ** 5 ? printf "%s «%-6.6sT» %s\n", $_{$_}, sprintf("%6.6
+f", "$_{$_}" / 1024 ** 4), $_ :
$_{$_} < 1024 ** 6 ? printf "%s «%-6.6sP» %s\n", $_{$_}, sprintf("%6.6
+f", "$_{$_}" / 1024 ** 5), $_ :
$_{$_} < 1024 ** 7 ? printf "%s «%-6.6sE» %s\n", $_{$_}, sprintf("%6.6
+f", "$_{$_}" / 1024 ** 6), $_ :
$_{$_} < 1024 ** 8 ? printf "%s «%-6.6sZ» %s\n", $_{$_}, sprintf("%6.6
+f", "$_{$_}" / 1024 ** 7), $_ :
printf "%s «%-6.6sY» %s\n", $_{$_}, sprintf("%6.6
+f", "$_{$_}" / 1024 ** 8), $_
for sort {$_{$a} <=> $_{$b} or $a eq "" ? 1 : $a cmp $b} keys %_;
- Not so good:
- I don't implement qw(-D --exclude-from -l -L --max-depth -S -X) like the real du does.
- I probably shouldn't do my own argument parsing, and I hope there's a better way to do the printing at the end.
- That being said,
You like? |