Linux - Sort directories by size

By xngo on June 17, 2019

# (A)
# Commands used: du, sort, awk
# It is fast.
du --max-depth=1 -k * | sort -nr | awk '{ if($1>=1024*1024) {size=$1/1024/1024; unit="G"} else if($1>=1024) {size=$1/1024; unit="M"} else {size=$1; unit="K"}; if(size<10) format="%.1f%s"; else format="%.0f%s"; res=sprintf(format,size,unit); printf "%-8s %s\n",res,$2 }'
 
 
# (B)
# Commands used: du, sort, cut, xargs
# It is slow because it uses "du" twice.
du --max-depth=1 -k | sort -nr | cut -f2 | xargs -d '\n' du -sh 2>/dev/null
 
# (C)
# Commands used: du, sort
# It requires GNU coreutils >= 7.5 because of 'sort -h'
du --max-depth=4 --human-readable | sort -h -r

Reference: http://ubuntuforums.org/showthread.php?t=885344

or simply use the application, NCurses Disk Usage

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.