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?
As of GNU coreutils 7.5 released in August 2009,
sort
allows a-h
parameter, which allows numeric suffixes of the kind produced bydu -h
:If you are using a sort that does not support
-h
, you can install GNU Coreutils. E.g. on an older Mac OS X:From
sort
manual:-h, --human-numeric-sort compare human readable numbers (e.g., 2K 1G)
There is an immensely useful tool I use called ncdu that is designed for finding those pesky high disk-usage folders and files, and removing them. It's console based, fast and light, and has packages on all the major distributions.
@Douglas Leeder, one more answer: Sort the human-readable output from du -h using another tool. Like Perl!
Split onto two lines to fit the display. You can use it this way or make it a one-liner, it'll work either way.
Output:
EDIT: After a few rounds of golf over at PerlMonks, the final result is the following:
As far as I can see you have three options:
du
to sort before display.sort
to support human sizes for numerical sort.You could also do
du -k
and live with sizes in KiB.For option 3 you could use the following script:
I've had that problem as well and I'm currently using a workaround:
This will not produce scaled values, but always produce the size in megabytes. That's less then perfect, but for me it's better than nothing (or displaying the size in bytes).
Found this posting elsewhere. Therefore, this shell script will do what you want without calling
du
on everything twice. It usesawk
to convert the raw bytes to a human-readable format. Of course, the formatting is slightly different (everything is printed to one decimal place precision).Running this in my
.vim
directory yields:(I hope 3.6M of color schemes isn't excessive.)
Here's an example that shows the directories in a more compact summarized form. It handles spaces in directory/filenames.
This version uses
awk
to create extra columns for sort keys. It only callsdu
once. The output should look exactly likedu
.I've split it into multiple lines, but it can be recombined into a one-liner.
Explanation:
Try it without the
cut
command to see what it's doing.Here's a version which does the sorting within the AWK script and doesn't need
cut
: