15

I'm using this command to determine which directory is eating my disk.

du -sk * | sort -n

How can I get human readable result form du for file sizes? I've checked man and all it have is -k flag which turns byte results to kilobyte results. I need results in gigabytes

4
  • 6
    For questions like this, you absolutely need to say which version of UNIX you're using (e.g. AIX 6.1, HP-UX 11i, Red Hat Linux, etc., etc.) Jul 1, 2013 at 19:11
  • and also refer to the man(manual) pages. man du
    – h3rrmiller
    Jul 1, 2013 at 19:49
  • @EightBitTony lesson learned. I'm on OSX btw
    – Mohsen
    Jul 1, 2013 at 20:53
  • How is ls related to this?
    – user
    Jul 1, 2013 at 21:27

2 Answers 2

15

This may work:

du -hs * | sort -h

If your copy of du doesn't support the -h flag, then you can convert the numbers using awk.

du -ks * | awk '
function human(x) {
    s="kMGTEPYZ";
    while (x>=1000 && length(s)>1)
        {x/=1024; s=substr(s,2)}
    return int(x+0.5) substr(s,1,1)
}
{gsub(/^[0-9]+/, human($1)); print}'
4
  • 1
    my du supports -h. works good but sort doesn't work as you expect now. 90G is smaller than 100K now!
    – Mohsen
    Jul 1, 2013 at 19:08
  • Are you sure sort -h does not work? I use it all the time in combination with du
    – Bernhard
    Jul 1, 2013 at 19:31
  • 2
    my sort doesn't have -h. I'm on OSX
    – Mohsen
    Jul 1, 2013 at 20:53
  • 1
    I should have made a note about that. The -h flag isn't very portable. You can use the awk option and sort before humanizing the numbers. Or, take a look at this: unix.stackexchange.com/a/4688/26112.
    – user26112
    Jul 1, 2013 at 20:55
4

On a Linux machine [Debian based], I get this when opening the man page for du:

 -h, --human-readable
              print sizes in human readable format (e.g., 1K 234M 2G)

Thus: du -h should give you what you need. Else, also from man du:

   --si   like -h, but use powers of 1000 not 1024

   -k     like --block-size=1K

I really wonder where you found your information.

2
  • Maybe the OP is using AIX, where du doesn't have a -h flag. Or HP-UX. Jul 1, 2013 at 19:11
  • Works on macOS as well, thanks! Apr 10 at 16:55

Not the answer you're looking for? Browse other questions tagged .