Linux Commands

How to Sort Du by Size in Linux

The disk usage or “du” command in Linux is a powerful utility for analyzing the storage that is occupied by files and directories. It displays all the files and their corresponding file size in blocks where each block measures 1024 bytes. Hence, the “du” command is essential for effective and efficient disk management.

However, the “du” command has no sorting feature which makes us question whether it’s possible. If that’s what you were searching for, don’t worry. In this guide, we will see how to use the “du” command and how to sort du by size in Linux.

How to Sort Du by Size in Linux

As mentioned, the “du” command doesn’t feature the sorting functionality, so we have to use another method. The “sort” command comes in handy in this situation. In this case, you can forward the output from the “du” command as an input to the “sort” command. First, type the command in the following syntaxes according to your requirements:

For ascending order: du -h [directory] | sort -h

For descending order: du -h [directory] | sort -rh

  1. The “-h” option presents the data in a human-readable format.
  2. The “-r” is for sorting in reverse order.

Let’s take an example of finding the bigger files in your home directory. In this situation, you might want to display the list in descending order.

du -h ~ | sort -rh

The tiles symbol (~) represents the home directory in Linux.

You can also display the top “N” directories by size using the “head” command alongside the previous commands. The syntax is as follows:

du -h [directory]  | sort -rh | head -n N

The “-n” means the number of lines to print and takes “N” as input. Replace “N” with the number of directories that you want to display. For instance, to find the top five files/directories in the home directory, you should use the following command:

du -h ~ | sort -rh | head -n 5

Furthermore, if you want to save these results in a text file, do it using the command as follows:

du -h [directory] | sort -rh > filename.txt

In the “filename.txt”, replace the filename with whatever name you want. The “>” symbol redirects the output to the specified file. If no file exists with your selected name, it creates a new one and saves the output.

For example, let’s save the data of the first five directories in the text file.

du -h ~ | sort -rh |head -n 5 > top_directories.txt

Conclusion

You can use the “du” command for effective disk management. But you need to sort the files according to their file size, and the manual process is time-consuming. Therefore, using the “sort” command, we explained the simple approach to sort du by size in Linux. Finally, we also covered how to limit the output to top “N” files and save those outputs in a file.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.