Wednesday 11 November 2009

Sort du output in readable format.

UPDATE: Download script from here

I got sick of typing "du -h --max-depth=1" all the time, and even then the output is not sorted. Unfortunately you cant use the sort util with the human readable output provided by du.

I found the awk part of this shell script in a forum somewhere and it works a treat.


#!/bin/bash
sudo du -k --max-depth=1 $1 | sort -nr | awk '
     BEGIN {
        split("KB,MB,GB,TB", Units, ",");
     }
     {
        u = 1;
        while ($1 >= 1024) {
           $1 = $1 / 1024;
           u += 1
        }
        $1 = sprintf("%.1f %s", $1, Units[u]);
        print $0;
     }
    '
 

This produces output like this;

884.0 MB .
385.5 MB ./Downloads
528.0 KB ./eBooks
48.0 KB ./My Shapes
32.0 KB ./1984_files
8.0 KB ./Xerox
8.0 KB ./My Pictures


Also, to avoid having to enter your password (for the sudo command) add this line to your sudoers file;


brettg ALL=NOPASSWD: /usr/bin/du