Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I need to get a list of human readable du output.

However, du does not have a "sort by size" option, and piping to "sort" doesn't work with the human readable flag.

For example, running:

du | sort -n -r

Outputs a sorted disk usage by size (descending):

du |sort -n -r
65108   .
61508   ./dir3
2056    ./dir4
1032    ./dir1
508     ./dir2

However, running it with the human readable flag, does not sort properly:

du -h | sort -n -r

508K    ./dir2
64M     .
61M     ./dir3
2.1M    ./dir4
1.1M    ./dir1

Does anyone know of a way to sort du -h by size?

share|improve this question
show 1 more comment

migrated from stackoverflow.com Sep 4 '09 at 13:06

This question came from our site for professional and enthusiast programmers.

33 Answers

http://dev.yorhel.nl/ncdu

command: ncdu

Directory navigation, sorting (name and size), graphing, human readable, etc...

share|improve this answer
1  
Great utility, but not installed by default on any OS I'm aware of. Not necessarily a problem, but one more program to have to look after... –  voretaq7 Nov 29 '11 at 23:07
add comment

Why not throw another hat into the ring.... it's an old question, but here's an example that is (mostly) pure shell script (fwiw) -- i.e, just bash and no perl/python/awk/etc. So in that sense maybe it offers something new to the discussion (or not). It calculates file size just once, but prints in various units (my preference). (The un-simplified version includes getopts that excludes "GB" if unwanted.)

#!/bin/bash

printf -- ' %9s %9s %9s       %-30s\n' 'K'        'M'        'G'        'Path'
printf -- ' %9s %9s %9s       %-30s\n' '--------' '--------' '--------' '-----------'
du -sk "$@" | while read val; do
    file=$(echo "$val" | cut -f2-)
    size_k=$(echo "$val"  | cut -f1)
    printf ' %9s %9s %9s       %-30s\n' \
          ${size_k}  \
          $(( size_k / 1024 ))  \
          $(( size_k / 1024 / 1024 ))  \
          "$file"
  done | sort -n
share|improve this answer
add comment

sort files by size in MB

du --block-size=MiB --max-depth=1 path | sort -n
share|improve this answer
add comment

protected by Mark Henderson Mar 11 '13 at 11:02

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.