1

On a Mac, using Bash, I tend to do

du -sh *

to tell the sizes of files and folders in the current directory, in MB and GB. But if I want to sort them by the sizes, I might do

du -sh * | sort -g

and it won't work well, because the M and G is not taken into account (so 44MB might be thought to be larger than 20GB, because 44 is greater than 20).

Is there a way not to write a program and just use UNIX commands and/or a Bash function to do that?

If I care about the files and folders that are in the GB range, I can do:

du -sh * | egrep "^\s*\d+(.\d+)?G\s" | sort -g

and it will show

2.6G    ski video clips
7.6G    trip 2012.mp4
 12G    trip photos  

but if TB or MB is to be considered, then the above will not work. Is there a way to do this more generally using UNIX / Mac OS X commands?

3
  • Does your sort command have a -h option? It's the same as du's -h – glenn jackman Apr 21 '15 at 1:02
  • it says invalid options (on OS X Yosemite). If there is, you would do du -sh * | sort -gh ? – nonopolarity Apr 21 '15 at 1:07
  • This doesn't strictly answer your question, but I usually use du -sk * | sort -n which lists the sizes in kilobytes. I find that easier to read than raw bytes. – Greg Hewgill Apr 21 '15 at 1:14
1

http://www.commandlinefu.com/commands/view/12927/list-the-size-in-human-readable-form-of-all-sub-folders-from-the-current-location says:

du -ks $(ls -d */) | sort -nr | cut -f2 | xargs -d '\n' du -sh 2> /dev/null

This is tested on a Mac and only runs du once. It has the minor error that 1K=1000 and not 1024:

du -sk * | sort -n | perl -pe '@SI=qw(K M G T P); s:^(\d+?)((\d\d\d)*)\s:$1.$SI[((length $2)/3)]."\t":e'
3
  • the above line doesn't work on the Mac... – nonopolarity Apr 21 '15 at 9:44
  • hm... and I think this solution uses 2 passes of du... maybe better if it can be 1 pass. But thanks for the commandlinefu.com pointer – nonopolarity Apr 21 '15 at 11:10
  • In practice the second pass is often done in cache: Size data is not very big so you have to have a small cache for it not to fit. – Ole Tange Apr 25 '15 at 21:06

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