Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How can I sort a list using a human-readable file-size sort, numerical sort that takes size identifier (G,M,K) into account? Can I sort "du -sh" output for example?

Problem: Consider the problem of listing files/folders and sorting them by their size. You can achieve that by running:

du -s * | sort -n

This lists the files/folders sorted by their sizes. However the printed size value is in bytes (or megabytes, or gigabytes if you choose).

It would be desirable to be able to sort based on the human-readable values, so I can run something analogous to

du -sh * | <human-readable file sort>

And have 1.5GB folder shows up after 2.0M.

share|improve this question

6 Answers 6

up vote 4 down vote accepted

Afaik, there's no standard command to do this.

There are various workarounds, which were discussed when the same question was asked over at Stack Overflow: How can I sort du -h output by size

share|improve this answer

Use GNU coreutils >= 7.5:

du -hs * | sort -h

(Taken from this serverfault question)

Man page

share|improve this answer
    
Thanks Jason. This ought to be the accepted answer. –  Brian Cline Dec 16 '13 at 8:27
1  
OSX doesn't have this option. You can use homebrew to brew install coreutils (which prepends all the coreutils commands with a 'g'). You can then do gdu -hs * | gsort -h. –  dsummersl Aug 7 at 22:17

If you are just worried about files larger than 1MB, as it seems you are, you can use this command to sort them and use awk to convert the size to MB:

du -s * | sort -n | awk '{print int($1 / 1024)"M\t"$2}'

Again, this rounds the sizes to the nearest MB. You can modify it converting to the unit of your choice.

share|improve this answer
    
This is similar to: du -sm * | sort -n. -s/-g makes du output sizes in megabytes/gigabytes. –  notnoop Sep 4 '09 at 8:35
    
For MB you have to divide by 1024 more. So it will be int($1 / (1024 * 1024)) –  Pratik Khadloya Jul 30 at 23:33

du -sk * | sort -n | awk '{ print $2 }' | while read f ; do du -sh "$f" ; done

share|improve this answer

Here's another one:

$ du -B1 | sort -nr | perl -MNumber::Bytes::Human=format_bytes -F'\t' -lane 'print format_bytes($F[0])."\t".$F[1]'

You might have to do a

$ cpan Number::Bytes::Human

first.

share|improve this answer

This command will sort by size in MB

du --block-size=MiB --max-depth=1 path | sort -n
share|improve this answer
    
That is already what the user is doing actually, he/she just didn't gave the example with MiB but mentioned about it. What he/she is looking for is to be able to sort when using the -h flag to du. –  Tonin Mar 11 '13 at 11:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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