How do I sort by human readable sizes numerically?

Try something like:

du -h folder | sort -h

Alternatives: -n for Numerical sorting

Note: the -h option of sort only exists in newer versions of Ubuntu.


Here is a more general approach. Get the output of du folder and du -h folder in two different files.

du folder > file1
du -h folder > file2

The key part is this: concatenate file1 and file2 line by line, with a suitable delimiter.

paste -d '#' file1 file2 > file3

(assuming # does not appear in file1 and file2)

Now sort file3. Note that this will sort based on file1 contents and break ties by file2 contents. Extract the relevant result using cut:

sort -n -k1,7 file3 | cut -d '#' -f 2

Also take a look at man sort for other options.


You may also save this as an alias, for later re-use. To do so, add the following to the bottom of ~/.bashrc:

sorted-du () {
    paste -d '#' <( du "$1" ) <( du -h "$1" ) | sort -n -k1,7 | cut -d '#' -f 2
}

Then, open a new terminal session and execute your new alias:

sorted-du /home

This answer is valid for 10.04.4LTS and lower versions of Ubuntu.

Unfortunatly the accurate answer which sorts K M G is difficult and complex:

You can alias the entire du command with one that sorts human readable using this

alias duf='du -sk * | sort -n | perl -ne '\''($s,$f)=split(m{\t});for (qw(K M G)) {if($s<1024) {printf("%.1f",$s);print "$_\t$f"; last};$s=$s/1024}'\'

which I found here

http://www.earthinfo.org/linux-disk-usage-sorted-by-size-and-human-readable/

just cd into the folder you would like to know then duf

you could add this duf alias to the end of your /home/user/.profile to make the duf command semi-permenant

results:

user@hostname:~$ duf
0.0K  Documenten
0.0K  Muziek
0.0K  Openbaar
0.0K  Sjablonen
0.0K  Video's
4.0K  backup_db.sql.g
4.0K  examples.desktop
12.0K xml printer ticket
52.0K hardinfo_report.html
152.0K    librxtxSerial.so
2.7M  jpos
4.4M  nxclient_3.5.0-7_amd64.deb
6.4M  nxnode_3.5.0-4_amd64.deb
6.8M  Downloads
7.4M  nxserver_3.5.0-5_amd64.deb
12.4M NetBeansProjects
18.1M mysqlworkbench.deb
28.3M Afbeeldingen
45.8M ergens-20110928-18.sql.gz
60.5M 2012-06-02ergens_archive.tar.gz
65.5M 2012-08-26ergens_archive.tar.gz
65.6M 2012-08-28ergens_archive.tar.gz
65.6M 2012-08-29ergens_archive.tar.gz
65.7M 2012-08-30ergens_archive.tar.gz
113.0M    Bureaublad
306.2M    ergens-20110928-18.sql

Here is why du -sch /var/* | sort -n does not work see the sorting of MKKMMKKMMK

user@hostname:~$ du -sch /var/* |sort -n

0 /var/crash
0 /var/local
0 /var/lock
0 /var/opt
8,0M  /var/backups
12K   /var/games
16K   /var/tmp
17M   /var/log
68M   /var/cache
104K  /var/spool
144K  /var/run
351M  /var/lib
443M  totaal
704K  /var/mail