Skip to main content

Linux Tips: Sorting Directories by Size

Linux Performance
By Keith Edmunds3 May 2017No Comments

Various Linux commands can present file and directory sizes in “human readable” format, where they append a “K” or “M”, etc, to indicate the file size; for example:

# du -sh *
960K auth.log.1
124K daemon.log
8.0K dpkg.log.5.gz
2.1M mcollective.log.3
56K messages

If we want to sort them by size, the sort command by itself isn’t much help. That’s because, by default, sort implements a lexical sort, and thus “2.1M” is sorted above “56K”, despite human beings recognising that the second is smaller:

# du -sh *|sort
124K daemon.log
2.1M mcollective.log.3
56K messages
8.0K dpkg.log.5.gz
960K auth.log.1

In a short list, it’s easy to see that the mcollective.log.3 file is the largest, but what if we have a long list? The sort command now takes a “-h” qualifier which understands the “human readable” format:

# du -sh *|sort -h
8.0K dpkg.log.5.gz
56K messages
124K daemon.log
960K auth.log.1
2.1M mcollective.log.3

Sorted, in more ways than one.

Could this Linux Tip be improved?

Let us know in the comments below.