Linux ls Command: Sort Files By Size

Posted on in Categories , , , last updated May 9, 2014

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.

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 -S -l
$ ls --sort=size -l
$ ls --sort=size *.avi
$ ls -S -l *.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

Sort output and print sizes in human readable format (e.g., 1K 234M 2G)

Pass the -h option to the ls command as follows:
$ ls -lSh
$ ls -l -S -h *.avi
$ ls -l -S -h ~/Downloads/*.mp4 | more

See ls(1) for more information.

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

24 comment

  1. The one thing I find most annoying about Linux “ls” is the fact that it (at least on Ubuntu) it sorts things in alphabetical order, no matter if it’s a dot file, or capitalized, or whatever. This highly offends my BSD-like sensibilities and makes me think linux “ls” belongs to DOS.

    Is there a way to make it stop this vile and pernicous behavior? ;)

Leave a Comment