Linux: Sort disk usage with awk

Sort the output of ‘du’ in human readable format (similar to the -h switch).

du -k | 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;
     }
    ' > du_sorted.txt

Comments are closed.