Find Largest File and Directory in Linux

Sometimes, Linux users may need to find the largest directory or the largest file on their disk drive. You can find this quickly with a single command. Let's see how it can be done.

In one of our previous articles, we saw in detail How to see the disk space usage for a file or folder using Linux terminal. The mentioned article refers to the "du" command which is able to calculate the summary size of a directory or a file. You can combine it with a few other console tools to find out the largest item. Here is how.

Find Largest File and Directory in Linux

To find the largest file and directory in Linux, you can combine du with the sort command. For example, you can execute du for a folder which contains subfolders like this:

du -hs ./distr/*

The -s switch tells du to print only the summary information.
The -h switch changes the size in the result from plain bytes to a human readable format.

See the following screenshot: linux-find-largest-file-or-folder

It is no problem when the folder you are analyzing is small. But if you are trying to check the whole file system, it can be very hard to review the full output of the du utility. The solution you can use is to combine du with the sort command.

The command will look as follows:

du -hs ./distr/*|sort -rh

The sort command combined with du via the pipeline character has two switches: -r and -h.
-h tells the command that the data to process is in human readable format.
-r makes the sort command order the data in reverse format

The output will be as follows: linux-largest-file-or-folder-sorted

This is very useful.

Now, let's shrink the output to a specific number of records. For example, let's see the top 5 biggest files and directories. Just combine du and sort with the head command.

du -hs ./distr/*|sort -rh|head -n 5

The argument -n for the head command specifies how many lines to include in the output. In my case, I want to see the top 5 largest lines.

The output is as follows: linux-largest-file-or-folder-sorted-top-5

That's it. Using the provided combination of commands, you can quickly find the largest file and directory in Linux. Just correct the root path for the du command and you are done.

Leave a Reply

Your email address will not be published. Required fields are marked *