Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: April 20, 2024
As Linux users, we frequently interact with the file systems. One of the common tasks is to list the files and sort them according to their size.
In this tutorial, we’ll discuss the various ways to achieve this.
Let’s create a set of files and directories to use as an example:
$ mkdir dir1 dir2
$ fallocate -l 850K dir1/file1.dat
$ fallocate -l 450M dir2/file2.dat
$ fallocate -l 750M dir1/file3.dat
$ fallocate -l 1.2G file4.dat
Let’s now look at the directory tree we just created:
$ tree -h
.
├── [4.0K] dir1
│ ├── [850K] file1.dat
│ └── [750M] file3.dat
├── [4.0K] dir2
│ └── [450M] file2.dat
└── [1.2G] file4.dat
2 directories, 4 files
We can use du and sort commands to list and sort files according to their size:
$ du -ah --max-depth=1 | sort -h
451M ./dir2
751M ./dir1
1.2G ./file4.dat
2.4G .
Let’s see the options we used for the du command:
We can use the -r option on the sort command to generate the output in descending order.
Also note that this approach is only suitable if we want to sort entire directories by size, not just individual files.
We can use a combination of ls, grep, and sort commands to list and sort files according to their size:
$ ls -lhR | grep '^-' | sort -k 5 -h
-rw-r--r-- 1 jarvis jarvis 850K Apr 12 21:47 file1.dat
-rw-r--r-- 1 jarvis jarvis 450M Apr 12 21:47 file2.dat
-rw-r--r-- 1 jarvis jarvis 750M Apr 12 21:47 file3.dat
-rw-r--r-- 1 jarvis jarvis 1.2G Apr 12 21:47 file4.dat
In the above example, the grep ‘^-‘ command excludes directories from the output.
Let’s now see the options we used for ls:
And for the sort command, we used:
Finally, we can use a combination of find and sort commands to list and sort files according to their size:
$ find . -type f -ls | sort -n -k7
2752740 852 -rw-r--r-- 1 jarvis jarvis 870400 Apr 12 21:47 ./dir1/file1.dat
2752741 460804 -rw-r--r-- 1 jarvis jarvis 471859200 Apr 12 21:47 ./dir2/file2.dat
2752742 768004 -rw-r--r-- 1 jarvis jarvis 786432000 Apr 12 21:47 ./dir1/file3.dat
2752743 1253380 -rw-r--r-- 1 jarvis jarvis 1283457024 Apr 12 21:47 ./file4.dat
Let’s have a look at the find command options we used:
And for the sort command, we used:
In this tutorial, we discussed three practical methods for listing and sorting files according to their size. The commands showed in this tutorial can be used in day-to-day life while working with the Linux system.