Quantcast
Channel: A standard tool to convert a byte-count into human KiB MiB etc; like du, ls1 - Unix & Linux Stack Exchange
Viewing all articles
Browse latest Browse all 21

Answer by Gilles 'SO- stop being evil' for A standard tool to convert a byte-count into human KiB MiB etc; like du, ls1

$
0
0

No, there is no such standard tool.

Since GNU coreutils 8.21 (Feb 2013, so not yet present in all distributions), on non-embedded Linux and Cygwin, you can use numfmt. It doesn't produce exactly the same output format (as of coreutils 8.23, I don't think you can get 2 digits after the decimal points).

$ numfmt --to=iec-i --suffix=B --padding=7 1 177152 48832200 1975684956
     1B
 173KiB
  47MiB
 1.9GiB

Many older GNU tools can produce this format and GNU sort can sort numbers with units since coreutils 7.5 (Aug 2009, so present on modern non-embedded Linux distributions).


I find your code a bit convoluted. Here's a cleaner awk version (the output format isn't exactly identical):

awk '
    function human(x) {
        if (x<1000) {return x} else {x/=1024}
        s="kMGTEPZY";
        while (x>=1000 && length(s)>1)
            {x/=1024; s=substr(s,2)}
        return int(x+0.5) substr(s,1,1)
    }
    {sub(/^[0-9]+/, human($1)); print}'

(Reposted from a more specialized question)


Viewing all articles
Browse latest Browse all 21

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>