Linux ls Command: Sort Files By Size

by on January 13, 2013 · 6 comments· last updated at January 14, 2013

How do I sort all *.avi or *.py files in $HOME/Download/ directory by file size using Linux ls command line utility?

The ls command is used to list directory contents under Linux and Unix like operating systems. If no options or operands are given, the contents of the current directory are displayed on the screen. By default entries are sorted alphabetically if none of the -cftuvSUX nor --sort option passed to the ls command.
Tutorial details
DifficultyEasy (rss)
Root privilegesNo
RequirementsGNU ls/BSD ls

The default output (sort by alphabetically)

Type the following command:

$ ls
$ ls *.py
$ ls *.avi

Sample outputs:

Fig.01: ls Command Output

Fig.01: ls Command Output

Force sort by size option

You need to pass the -s or --sort=size option as follows:
$ ls -s
$ ls --sort=size
$ ls --sort=size *.avi
$ ls -s *.avi

Sample outputs:

Fig.02: Sort files / folders (directories) by size

Fig.02: Sort files / folders (directories) by size


You will see largest file first before sorting the operands in lexicographical order. The following command will sort file size in reverse order:
$ ls -l -S | sort -k 5 -n
OR try (see comments below, thanks!):
$ ls -lSr
Sample outputs:
Fig.03: Ls Command Sort By Size in Reverse (Lowest First) Order

Fig.03: Ls Command Sort By Size in Reverse (Lowest First) Order



You should follow me on twitter here or grab rss feed to keep track of new changes.

Featured Articles:

{ 6 comments… read them below or add one }

1 Raphael January 13, 2013 at 8:27 pm

Instead of
$ ls -l -S | sort -k 5 -n
this works also
$ ls -l -S -r

-r = reverse order

Reply

2 Roy January 13, 2013 at 10:24 pm

Or just do

ll -Sr

:)

Reply

3 dru January 14, 2013 at 2:10 pm

ll is alias to ‘ls -l’. Although it it configured on many linux distros, it does not have to be and therefore not guaranteed to work.

Reply

4 dru January 13, 2013 at 8:51 pm

Even better is:
$ ls -lrS

Reply

5 nixCraft January 14, 2013 at 11:49 am

Raphael, Roy, and dru,

Thanks for the heads up. The faq has been updated.

Reply

6 george January 15, 2013 at 8:17 am

what I do is this:
du -xak . | sort -n | tail -100
it finds me the biggest 100 files or directories on the filesystem I’m in

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <kbd> <blockquote> <pre> <a href="" title="">

Tagged as: , , , ,

Previous Faq:

Next Faq: