How can I sort du -h output by size
Solution 1
As of GNU coreutils 7.5 released in August 2009, sort
allows a -h
parameter, which allows numeric suffixes of the kind produced by du -h
:
du -hs * | sort -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:
brew install coreutils
du -hs * | gsort -h
From sort
manual:
-h, --human-numeric-sort compare human readable numbers (e.g., 2K 1G)
Solution 2
du | sort -nr | cut -f2- | xargs du -hs
Solution 3
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.
Solution 4
@Douglas Leeder, one more answer: Sort the human-readable output from du -h using another tool. Like Perl!
du -h | perl -e 'sub h{%h=(K=>10,M=>20,G=>30);($n,$u)=shift=~/([0-9.]+)(\D)/;
return $n*2**$h{$u}}print sort{h($b)<=>h($a)}<>;'
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:
4.5M .
3.7M ./colors
372K ./plugin
128K ./autoload
100K ./doc
100K ./syntax
EDIT: After a few rounds of golf over at PerlMonks, the final result is the following:
perl -e'%h=map{/.\s/;99**(ord$&&7)-$`,$_}`du -h`;die@h{sort%h}'
Solution 5
du -k * | sort -nr | cut -f2 | xargs -d '\n' du -sh
Related videos on Youtube
Tom Feiner
Updated on September 17, 2022Comments
-
Tom Feiner over 1 year
I need to get a list of human readable du output.
However,
du
does not have a "sort by size" option, and piping tosort
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?-
cregox over 8 yearsHere's a much related question: serverfault.com/q/737537/35034
-
SDsolar over 6 yearsHave you seen this one? unix.stackexchange.com/questions/4681/… It is a near duplicate and is worth gold. You do a normal
du
but add the -h to thesort
command. You can add-rh
so the largest are first in the file, otherwise you needtail
to see the space hogs. -
Cees Timmerman almost 3 yearsSee also superuser.com/questions/300606/… for a friendlier alternative (
ncdu
).
-
-
Douglas Leeder about 15 yearsAnd it'll do a huge amount of duplicate counting.
-
Tom Feiner about 15 yearsI like th -BM switch, which is basically the same as -m, but it has the advantage of displaying the size and M postfixed to it, so you get 10M which is much clearer than just 10 :)
-
macb about 15 yearsthat's what xargs does ;-)
-
hasen about 15 yearsit would help if you explain why that works??
-
Douglas Leeder about 15 yearsFirst it does the normal du - then for each entry it recalculates the size just to print it in human readable form.
-
Antonio Diaz about 15 yearsI have a Perl answer, too, but I think it might make people hate me: du -B1 | sort -nr | perl -e '%h=(0=>b,1=>K,2=>M,3=>G);for(<>){($s,@f)=split/\s+/;$e=3;$e-- while(1024**$e>$s);$v=($s/(1024**$e));printf "%-8s%s\n",sprintf($v >= 100 ? "%d%s" : "%.1f%s",$s/(1024**$e),$h{$e}),@f;}'
-
Antonio Diaz about 15 yearsEven though the Perl answer actually gives its formatting much closer to du. Although the rounding is off... It looks like du always gives ceil() rather than round()
-
macb about 15 years@Douglas Leeder: you are right for the duplicate counting, but think that the second du does not start from cold cache (thanks to the OS) @hasen j: xargs is a very useful command, it splits its stdin and feeds it as arguments to the given command
-
Admin about 15 yearshehe, I always forget about xargs. ;) At the end of the day, whatever gets the job done imo.
-
Antonio Diaz about 15 yearsHey, why did I use a hash there? Should've been an array... morning-brain grumble....
-
Admin about 15 yearsThat doesn't give the human-readable output, though, which is what the OP was looking for.
-
Admin about 15 yearsDon't really care about reputation score, but I am a bit confused as to why this answer has 12 votes when my more or less identical answer below has none.
-
Antonio Diaz about 15 yearsAdded a better Perl solution as another answer.
-
hipe about 15 yearsChris's is actually superior since it works with paths containing whitespace. Throwing a vote your way, buddy.
-
Joachim Sauer about 15 years+1 for one of the rare, valid exceptions to "do one thing and do it right". Unless someone gets sort to understand the SI-prefix and/or the binary prefixes.
-
ojblass almost 15 yearsVery nice... I wondier if the results could be fed to standard out... I am so lazy that I cannot read the manual
-
Alberto over 14 yearsTwo reasons: most folks just vote for the first good answer they see, and secondly, many people don't know what the -k option to du does.
-
Dennis Williamson over 14 yearsYour short version outputs on
stderr
because of thedie
can you change it to make it output onstdout
? -
Antonio Diaz over 14 yearsChange the
die
to aprint
and it will go tostdout
. It's just two more characters. -
Bill Weiss about 14 yearsAt least here, that doesn't work.
houdini@clanspum:~/ > ls -1Ssh | grep clanspum 4.0K drwxr-xr-x 27 houdini users 4.0K 2010-02-15 12:35 clanspum/ 0 drwxr-xr-x 2 houdini users 77 2010-02-15 13:06 clanspum-s/ houdini@clanspum:~/ > du -sh clanspum/ 602M clanspum/
-
Bill Weiss about 14 years... pretend that was formatted correctly. Point is, it shows a directory as being "4.0K", while
du -sh
shows "602M". The latter is correct. -
user2910702 almost 14 yearsAnd as ptman mentions below: ta da! (new
sort
flag) -
user2910702 almost 14 yearsgt5 is in the same vein; its killer feature is displaying growth.
-
Vi. over 13 yearsBoth versions fail when filenames contain spaces
-
wodow about 13 yearsThe relevant section of the manual: gnu.org/software/coreutils/manual/…
-
Richard Poirier about 13 yearsEasy to install on OS X with homebrew -- brew install coreutils.
-
anthony about 13 yearsthank you! this is the first example that works for me in OS X 10.6 not counting the perl/phython-scripts. and thanks again for the good explanation. always nice to learn something new. awk sure is a powerful tool.
-
voretaq7 over 12 yearsUgly, but cross-platform :).
-
voretaq7 over 12 yearsGreat 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...
-
ThorstenS over 12 yearswow, thanks. Much better thank my evergreen
du -sk * | sort -n
-
JacketSnatcher about 12 yearsworks on ubuntu!
-
chutz almost 12 yearsGood one! I personally always did
du -BM | sort -nr
as a workaround - it is human readable enough, and it is sorted, if anyone is stuck with older coreutils. -
nandoP over 10 yearsimpressive perl hackistry
-
Brian Cline over 10 yearsIf using on OSX via Homebrew, note that you'll now need to use gsort rather than sort:
du -hs * | gsort -h
-
Paul Draper over 10 years@chutz, that puts
168K
before104M
. -
chutz over 10 years@PaulDraper,
du -BM
prints everything in megabytes, so a file that is 168K would actually display as 0M. Unless there is some other version discrepancy I am not aware of. My version ofdu
only shows integer megabyte values. -
Paul Draper over 10 years@chutz, yes.
du -sBM * | sort -nr
does work. -
RSFalcon7 about 10 yearsThe result is in reverse order :(
-
laggingreflex over 9 years
-
laggingreflex over 9 yearsCan't use with
du -k --total
, gives error at the enddu: cannot access 'total': No such file or directory
-
laggingreflex over 9 yearsPerfect. @RSFalcon7 To un-reverse order just change it to
sort{h($a)<=>h($b)}
or make itreverse sort{..
-
zegkljan about 9 yearsi think if it is a very big number, then the unit is gone and the number displayed is small... try
23423423432423
-
shaheen almost 9 yearsIf using on FreeBSD, try gsort instead sort.
-
BurninLeo over 8 yearsThat's really cool! And much faster than hanging around with
du
, if you just want to identify the large directories. -
mwfearnley over 8 yearsThe way
sort -h
seems to work is to sort by the suffix first, and then by the numeric value. e.g. 2000 is deemed to be less than 1K. This would be fine in most autogenerated listings though, where a smaller number will never have a larger suffix then a larger number. -
Paul Gear over 8 yearsThat's not a great solution, because it traverses the file system twice.
-
Jeff Olson over 8 yearsThis is the simplest solution I've seen so far on this page, thank you!
-
Mau over 8 yearsi like this one more any other answer. how would you go to show only the first 50 results?
-
HankCa over 8 yearsMacOSX by default (i.e. outside of home-brew) doesn't support a proper
xargs
so this form was necessary. However for files with spaces in them you need to set IFS:IFS=$'\n'
-
pojo over 7 yearsStandard
du
on OS X does not support the suggested options, but the one from coreutils does (gdu
)gdu -hs * | gsort -h
-
HankCa over 7 yearsGreat thanks for that. I changed the du to
du -sh *
to show just the immediate files and directories without recursive descent. -
Adam Katz about 7 yearsThe BSD
du -d 1
syntax has been supported by GNU du since coreutils 8.6 was released in 2010 (though its first Red Hat availability was RHEL 7 in 2014), so you no longer need--maxdepth=1
. I only found out about this recently myself. -
jasonology almost 7 yearsJust tried this on macOS Sierra. Works as expected. Nice!
-
Samuel Lelièvre about 6 years@Mauro -- just pipe the result to
head
by adding ` | head -50` at the end. -
Mike Turley about 6 yearsFor future Google users like myself, if you want to use this answer's command but sort by size descending instead of ascending, you just need the
-r
option forsize
. To scroll a list of the largest stuff, usedu -hs * | sort -hr | less
. -
giorgio79 almost 6 yearsThis solution does not work on hidden directories that start with a "." like ".git"
-
ptman almost 6 years@giorgio79 in that case, use
* .??*
-
vladkras almost 6 yearsI use
du -sh ./* | sort -g
cause-h
is not supported on BusyBox v1.27.2 -
Tripp Kinetics over 5 yearsLoosely based on this one-liner, I created a script for providing a human-readable, sorted du(1) output. Please refer to my answer, serverfault.com/a/937459/218692.
-
Selwyn Polit over 5 yearsI like to show the top ten sorted largest to smallest with
du -sh * | sort -h -r | head -n 10
-
Marco Marsala about 5 yearsSimpler:
du -h | sort -h
-
mjs almost 5 yearsThis is the best, but does not account for bytes (with G,M, K) . Otherwise, nearly perfect!
-
neverMind9 almost 5 yearsFor me,
sort
itself already has that feature.gsort
is not pre-installed. -
baptx almost 4 yearsWhat is the best practice between
du -hs *
anddu -h -d1
? -
ptman almost 4 years@baptx They're different things. Do you want dotfiles or not?
-
baptx almost 4 years@ptman thanks, indeed I want to see everything, including files and folders starting with a dot but
du -hs *
did not display them. In this case, you should add to your answer that we have to usedu -h -d1
. -
adfaklsdjf over 3 yearsStruggling with getting this into a bash alias or function.. it doesn't seem to like the 3 backticks...
-
John Hamilton over 3 yearsHoly hell, that PerlMonks page seems like they're talking in some ancient language...
-
David Okwii about 3 yearsAdd the -r option to sort in descending order as in " du -sh * | sort -hr"
-
cregox almost 3 yearshighly recommend using
du -chxd 1
rather than summary. it's much more informative! 😁 -
yankeemike over 2 yearsIf I'm in a directory and I want to list the files in reverse size order I do
du -h | sort -rh