I often work on unix boxes that don't have the -h flag for du.
I am looking for a one-liner to convert KB to human readable. Perl seemed like a good choice.
This is what I have so far.
@a=split /\s+/;
$x=$_!=0?int(log()/log(1024)):0;
@b=('K','M','G');
printf("%.3s%s\t%s\n",$_/(1024)**$x,$b[$x],$a[1]);
Run like this:
du -ks * | perl -lne '@a=split /\s+/;$x=$_!=0?int(log()/log(1024)):0;@b=('K','M','G');printf("%.3s%s\t%s\n",$_/(1024)**$x,$b[$x],$a[1]);'
It doesn't work perfectly as I haven't been able to find the correct printf format.
one-liners using perl as well as awk/sed, etc. would be the most useful.
This is what du -h looks like. Max 1 decimal. Min: 0 decimals. With Rounding.
8.0K
1.7M
4.0M
5.7M
88K
Update:
du -ks * | perl -lane '$F[0];$x=$_!=?int(log()/log(1024)):0;printf("%.3s%s\t%s\n",$_/1024**$x,qw<K M G>[$x],$F[1]);'
If the only modification you want to make (It's not clear what you want) is to have the number be right-aligned in a field of 3 characters, simply drop the period from the printf format. Also, rather than explicitly calling
split
and treating the whole of$_
as a number, I would recommend passing Perl the-a
switch, which automatically splits$_
on whitespace into the array@F
, and then replace the references to$_
in your code with$F[0]
.Your code could thus be rewritten (using a couple more Perlisms and adding some spaces for readability) as: