The Linux ls command is a handy tool for listing files inside a directory. In the past, we have covered how to list and sort files by last modification time using the ls command.
In this article, we will go a step further and explore ways that you can list all the files in a specific directory and sort them by file size.
List or Sort All Files by Size in Linux
To list all files contained in a directory, launch your terminal and run the following command. When invoked without any arguments, the ls command simply lists the files and folders inside a directory.
$ ls
In the following command the -l
flag means long listing and -a
tells ls to list all files including hidden files – which are prefixed by a period (.)
. To avoid displaying the .
and ..
files, use the -A
option instead of -a
.
$ ls -la
List All Files Ordered by Size
To list all the files and sort them by size, use the -S
flag. By default, it displays output in descending order (biggest to smallest in size).
$ ls -laS
You can display the output in a human-readable format by appending the -h
option as shown.
$ ls -laSh
In addition, you can sort in reverse order (from the smallest to the largest) by adding the -r
option as shown.
$ ls -laShr
List or Sort Files by Size According to a Specific File Type
You can list or sort out files by size by applying file type as a filter. For example, to list or sort zipped files by size, use the wildcard symbol as shown.
$ ls -lhS *.zip
Exclude Directories When Listing or Sorting Files by Size
To exclude directories in listing or sorting files by size, use the following syntax:
$ ls -Slh | grep -v '^d'
List or Sort All Files Using a Common Unit Size
In the above examples, the file sizes have been printed in different unit sizes, i.e Kilobytes (k) and Megabytes (M).
To print or display all file sizes in a specific unit, for example in Megabytes, add the --block-size=
option specifying Megabytes as M
as shown below.
$ ls -laS --block-size=M
From the output, you can see the file sizes are now in MB only.
You can also print the size in KB units by replacing M with k:
$ ls -laS --block-size=k
This time around, the file sizes are accurately displayed in kilobytes since no file is less than a kilobyte, and hence no rounding off to the nearest kilobyte is done.
Conclusion
And that’s it for this lecture. In this article, we have demonstrated how to list or sort files by size in Linux. We hope you found this information insightful.