How can I sort all files by size in a directory?

51

8

How can I display the files in a unix directory sorted by their human readable size, going from largest to smallest?

I tried

du -h | sort -V -k 1 

but it does not seem to work.

user46976

Posted 2011-12-16T21:16:01.583

Reputation: 1 078

Can you please clarify if you are expecting the subdirectory sizes to appear in the output too, and also if you are looking for the apparent size of the files or the actual size they use on disk ? – jlliagre – 2011-12-17T13:42:34.167

Answers

57

ls(1) /sort:

-S     sort by file size

Hello71

Posted 2011-12-16T21:16:01.583

Reputation: 7 636

1-S is no longer a valid sort argument at least on ubuntu. The below answer by @alex worked for me. The answer link is https://superuser.com/a/990437/528836. – Prasanna – 2017-12-21T05:36:51.677

35

$ ls -lhS

-l     use a long listing format
-h     with -l, print sizes in human readable format (e.g., 1K 234M 2G)
-S     sort by file size

kev

Posted 2011-12-16T21:16:01.583

Reputation: 9 972

16

If you have the appropriate sort version you may simply use:

du -h | sort -rh

mine is

$ sort --version
sort (GNU coreutils) 8.12

ztank1013

Posted 2011-12-16T21:16:01.583

Reputation: 451

4

du -ha | sort -h

du : estimate file disk usage.

-h : for human
-a : all files

sort : sort lines of text.

-h : for human

man du; man sort for more. It works for me on ubuntu v15.

Andrew_1510

Posted 2011-12-16T21:16:01.583

Reputation: 241

4

ls -S wasn't an option on the OS for me. The following worked:
ls -l | sort -k 5nr
They "key" was to specify the column to sort (get it, the "key"). Above I'm specifying -k 5nr meaning sort on 5th column which is size (5) evaluated as a number (n) in descending order (n)

Reference sort documentation for more information

Alex

Posted 2011-12-16T21:16:01.583

Reputation: 208

1

I got this to work for me:

ls -l | sort -g -k 5 -r

Which (I just figured-out) is the same as:

ls -lS

Aaron

Posted 2011-12-16T21:16:01.583

Reputation: 752

0

Unlike ls -S, this will properly handle sparse files:

ls -lsh | sort -n | sed 's/^[0-9 ]* //'

jlliagre

Posted 2011-12-16T21:16:01.583

Reputation: 12 469