Pages

2009-09-29

Shell function to print "du -s" output in ascending order of the size

I ran in a problem where a du -sh output showed me the disk usage in human readable format (GB, MB, etc) but the output order was based on file names and not on the size. So I wrote this little awk (gawk) wrapper:

Declaration:

function duh_sorted {
    du -s $*|sort -n|\
    awk 'BEGIN { m = 1024; g = m*m; t=g*m} { \
    \
    if($1>t) { human_size=$1/t; unit="TB"; } \
    else { \
        if($1>g) { human_size=$1/g; unit="GB"; } \
        else { \
            if($1>m) { human_size=$1/m; unit="MB"; } \
            else { human_size=$1; unit="KB";} \
            } \
    } \
    printf("%4ld %c\t%s\n", human_size,unit,$2)
    }'
}

Usage:

$ duh_sorted /data/nfs/*

   8 K  /data/nfs/scripts
  32 K  /data/nfs/extensions
 151 M  /data/nfs/patches
 197 M  /data/nfs/logs
   3 G  /data/nfs/filerepo
  14 G  /data/nfs/mondo

 
$ duh_sorted /
 44 G  /


That's it!

No comments:

Post a Comment