Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kilobytes to human readable. Looking for one liner

Tags:

sh

sed

awk

perl

du

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]);'
like image 363
user606723 Avatar asked Dec 07 '25 08:12

user606723


1 Answers

This uses Number::Bytes::Human from CPAN:

du -ks * |perl -MNumber::Bytes::Human=format_bytes -nle \
    '@F=split(/\s+/,$_,2); printf("%-10s%s\n", format_bytes($F[0]*1024), $F[1])'

EDIT: Without using modules:

du -ks * |perl -nle \
   '@F=split(/\s+/,$_,2); $b=$F[0]*1024; for($i=0;$b>1024;$i++){$b/=1024} $u=qw{B K M G T}[$i]; printf("%10.".($b=~/\./?1:0)."f$u  %s\n", $b, $F[1])'
like image 197
MisterEd Avatar answered Dec 09 '25 00:12

MisterEd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!