FormatFileSizes

From time to time people ask how to sort the output of du -h. This is not particularly easy, since du -h is intended to be read by a human rather than parsed by a program.

You can use awk to format the output of du after it has been sorted:

du dir | sort -n | \
awk 'BEGIN {u[0]="K";u[1]="M";u[2]="G";}
     { size=$1;sub(/^[^\t]+\t+/,"");name=$0
       for (i=3;i>=0;--i) {
         if ( size > 1024 ^i)
            {printf "%.2f%s\t%s\n",(size / 1024^i),u[i],name;next}}}'