Over time your PC gets cluttered with all sorts of different files if you’re not careful with them. If you’re using your Linux PC as a development machine, there’s a good chance that most of your directories are littered with random files.
In this article, we’re talking about how you can use the find and du commands from the Linux terminal to find large files and directories in Linux.
Also read: How to shutdown Linux from Command Line?
How to find large files in Linux using the find command?
The find command allows users to search for files and directories using different criteria, including file sizes. Here’s what command you will use if you were looking for files larger than 50 MB.
sudo find . -xdev -type f -size +50M
This command will output a list of all files in the current directory larger than 500 MB. Note that you can also use the find command in combination with commands like ls or sort to perform file management and other operations.
For example, if you wanted to print the files in the active directory, larger than 50 MB sorted according to file size and in human-readable format, here’s what you would do.
find . -xdev -type f -size +50M -print | xargs ls -lh | sort -k5,5 -h -r
The command above is split into different parts. We first use the find command to find the files. We then pipe the output to ls to fetch file names, and finally, we use the sort command to sort the files according to the 5th column, which is file size.
- find . -xdev -type f -size +50M -print: This is the find command. It finds the files (-type f) in the current working directory, indicated by the period (.) according to the given criteria (-size 50M).
- xargs ls -lh: The output of the file command is piped to ls -ls using xargs.
- sort -k5,5 -h -r: This is where the sorting happens according to the 5th column of ls -lh, which is the file size.
There are many other things you can do with the find command as well, including searching for files using file age in days.
How to find large files and directories using the du command?
The du command is generally used for file space estimation. However, it can also come in handy if you’re looking for files or folders that take up large spaces on your drive.
Do keep in mind to not confuse this command with DF, which is used to check disk space instead.
For example, the command below will print out the three largest files in the currently active directory.
du -ahx . | sort -rh | head -3
Here’s a breakdown of the command.
- du -ahx: Estimates file sizes in the current active directory and prints it in a human-readable format.
- sort -rh: Sorts the output given by the du command using the human-readable value (h) and reverses the result.
- head -3: Prints the first three lines of the output.
Someone who writes/edits/shoots/hosts all things tech and when he’s not, streams himself racing virtual cars. You can reach out to Yadullah at [email protected], or follow him on Instagram or Twitter.