Friday, 1 February 2013

Linux ls Command: Sort Files By Size

Linux ls Command: Sort Files By Size


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


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








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

No comments:

Post a Comment