A humble offering, hoping to find a place where its perlishness won't be scorned. On another site, I got a little obsessed with this question I came across:
How can I get sorted, human-readable output from du? It doesn't have a sort option, so you have to pass it to another program, like sort:
Update: Thanks to hbm, grinder, and Roy Johnson, a significantly smaller version has been golfed (putting it here because it's buried around ^7 in the comments):
But if you want human-readable output, you can't do that, because sort can't sort it numerically. Others were offering shell solutions that invoked du on each item twice, once before being passed through sort, and once after for the human-readable verison. Wasteful! After finding solution in Awk, I wrote this "one-liner":du | sort -nr
But then I realized it'd probably be better to use Perl for the sorting, and got this shorter result:du -B1 | sort -nr | perl -e '@h=qw(b K M G);for(<>){($s,@f)=split/\s+/ +;$e=3;$e-- while(1024**$e>$s);$v=($s/(1024**$e));printf "%-8s%s\n",sp +rintf($v>=100?"%d%s":"%.1f%s",$v,$h[$e]),@f;}'
Both of them return human-readable disk usage output, sorted largest item first:du -h | perl -e 'sub h{%h=(K=>10,M=>20,G=>30);($n,$u)=shift=~/([0-9.]+ +)(\D)/;return $n*2**$h{$u}}print sort{h($b)<=>h($a)}<>;'
I almost posted this to the 'Obfuscation' area, but I thought this would be more appropriate. I am prepared to do penance if I was mistaken.4.4M . 3.6M ./colors 372K ./plugin 128K ./autoload 100K ./syntax 100K ./doc
Update: Thanks to hbm, grinder, and Roy Johnson, a significantly smaller version has been golfed (putting it here because it's buried around ^7 in the comments):
perl -e'%h=map{/.\s/;99**(ord$&&7)-$`,$_}`du -h`;die@h{sort%h}'
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: du -h, sorted
by grinder (Bishop) on Feb 25, 2009 at 21:56 UTC | |
by Roy Johnson (Monsignor) on Feb 25, 2009 at 22:58 UTC | |
by grinder (Bishop) on Feb 26, 2009 at 00:17 UTC | |
by hbm (Hermit) on Feb 26, 2009 at 03:00 UTC | |
by bellaire (Hermit) on Feb 26, 2009 at 15:41 UTC | |
by hbm (Hermit) on Feb 26, 2009 at 16:28 UTC | |
| |
by hbm (Hermit) on Feb 25, 2009 at 23:09 UTC | |
Re: du -h, sorted
by Tanktalus (Canon) on Feb 27, 2009 at 00:48 UTC | |
Re: du -h, sorted
by hbm (Hermit) on Feb 27, 2009 at 17:56 UTC | |
Re: du -h, sorted
by DrHyde (Prior) on Feb 26, 2009 at 11:01 UTC |
Back to
Cool Uses for Perl