- Поиск больших файлов Linux
- Поиск больших файлов Linux
- 1. GDMap
- 2. Утилита ncdu
- 3. Утилита du
- 4. Утилита find
- Выводы
- How to Find Large Files in Linux
- Content
- Use the ls Command
- Use the find Command
- Use the du Command
- Find Large Unused Files
- GUI Apps to Find the Largest Files in Linux
- Disk Usage Analyzer
- Remove the Largest Files
- Frequently Asked Questions
- Why I am getting a «permission denied» error?
- How do I find files larger than 1GB?
- How can I view the size of a particular folder?
- How to Find Out Top Directories and Files (Disk Space) in Linux
- How to Find Biggest Files and Directories in Linux
- Find Largest Directories in Linux
- Find Out Top File Sizes Only
Поиск больших файлов Linux
Если на вашем жёстком диске закончилось свободное пространство, самый простой способ его освободить — найти и удалить самые большие и при этом ненужные файлы. Такая задача может возникнуть как на сервере, так и на домашнем компьютере, поэтому существуют удобные решения для обоих ситуаций. Способов поиска больших файлов существует очень много.
Как вы уже поняли, в этой небольшой инструкции мы рассмотрим, как найти большие файлы Linux с помощью графического интерфейса или консольных утилит. Будем двигаться от самого простого к более сложному.
Поиск больших файлов Linux
1. GDMap
Несмотря на то, что графических утилит есть около десятка, все они мне не очень нравятся. Например в Gnome можно использовать GDMap, а в KDE — fileslight. Обе утилиты сканируют файловую систему и выводят все файлы в виде диаграммы. Размер блока зависит от размера файла. Чем больше файл или папка, тем больше блок. Для установки GDMap в Ubuntu выполните:
Затем запустите утилиту из главного меню. По умолчанию она отображает домашнюю папку. Здесь можно оценить, какие файлы самые увесистые.
2. Утилита ncdu
Это псевдографическая утилита, которая работает в терминале Linux. Она отображает список файлов и директорий по объёму и, что самое интересное, тут же позволяет удалять ненужные файлы. Для установки утилиты выполните:
Затем запустите утилиту, передав ей в качестве параметра папку, которую надо просканировать. Можно проверить ту же домашнюю папку:
У утилиты очень простое управление. Для перемещения по списку используйте кнопки со стрелками вверх и вниз, для открытия папки — клавишу Enter, а для удаления файла — кнопку d. Также можно использовать для перемещения кнопки в Vim стиле — h, j, k, l.
3. Утилита du
Если у вас нет возможности устанавливать новые утилиты, может помочь установленная по умолчанию во всех дистрибутивах утилита du. С помощью следующей команды вы можете вывести 20 самых больших файлов и папок в нужной папке, для примера снова возьмём домашнюю папку:
sudo du -a /home/ | sort -n -r | head -n 20
Мы не можем использовать опцию -h для вывода размера в читабельном формате, потому что тогда не будет работать сортировка.
4. Утилита find
С помощью команды find вы тоже можете искать большие файлы Linux. Для этого используйте опцию -size. Например, давайте найдём файлы, которые больше 500 мегабайтов в той же домашней папке:
sudo find /home -xdev -type f -size +500M
Можно пойти ещё дальше — вывести размер этих файлов и отсортировать их по размеру:
find / -xdev -type f -size +100M -exec du -sh <> ‘;’ | sort -rh
Самые большие файлы Linux будут сверху, а более мелкие — ниже.
Выводы
В этой небольшой статье мы разобрались, как выполняется поиск больших файлов Linux. После того, как вы их нашли, остаётся выбрать ненужные и удалить, если подобное происходит на сервере, то, обычно, это логи различных сервисов или кэш. Обратите внимание, что после удаления файлов место в файловой системе может и не освободится. Для полного освобождения места следует перезагрузить компьютер. Это довольно частая проблема на серверах и VPS.
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
How to Find Large Files in Linux
Identifying large files on your PC can help you quickly reclaim some much needed space. For desktop Linux users, hunting down large unnecessary files might be optional. But when it comes to server space, it costs money, and you have to pay for that excess space every month. Here’s how you can locate big files in Linux to quickly get rid of them.
Content
Use the ls Command
Generally, the ls command is used to list all of the directories and files in the Linux terminal. However, it can do much more – for instance, classify directory contents and display file sizes.
- To see more information about files and directories including their permissions, you can use the -l flag.
- To print their size along with all of the information, use the -s flag along with the previous -l flag.
- By default, the ls command will only list the directories. To see the files inside the directories recursively, use the -R flag.
- To sort files, you can use two methods. One takes advantage of the -S flag inside the ls command, while the other employs the power of the sort command. To sort the files according to their file size in descending order, run the following command:
- Alternatively, after the ls command returns, you can pipe the result into the sort command. This will sort the list as per their numerical file sizes in ascending order. You can also reverse the order by using -r flag in conjunction with the sort command.
- So far, we have analyzed and found the largest files inside our current working directory. To identify the largest file in your whole filesystem, you can add the location after the ls command.
Use the find Command
The find command can be used to search any files inside a Linux filesystem. In this case, we can employ it to list files according to their file sizes. We can also filter the results by minimum file size.
find ./test -type f -size +100M
- Doing so will find all the files inside the “test” directory which has a size greater than 100MB.
- Sometimes you need to search the entire filesystem to find the largest file. For that, just add a / after the find command.
sudo find / -xdev -type f -size +100M
Note: the -xdev flag instructs not to descend directories on other filesystems. In simple words, it won’t scan other mounted filesystems in your Linux system.
- To remove this behavior and to scan all the mounted drives along with your primary filesystem, just remove the -xdev command as follows:
sudo find / -type f -size +100M
Now you should be able to view the list of the largest files in your entire device along with your mounted drives.
Use the du Command
The du command is primarily designed to estimate file sizes in Linux. Here’s how to find large files with it.
- The file sizes listed here appear as very long number strings, so they are very hard to estimate. To make it readable, use the -h flag in conjunction with other flags.
- To make the file size uniform, use the blocksize operator -B along with a unit of your choice. If you want to convert the sizes in MB, use unit M as a block size.
- To find the largest files among them, use the sort command to sort the files in descending order.
du -aBM | sort -nr | head -n 5
- So far we’ve been displaying file sizes only in our current working directory. To list the largest files of a specific directory, append the directory name after the du command. The following command will list the five largest files in your home directory.
du /home -aBM | sort -nr | head -n 5
du / -aBM | sort -nr | head -n 10
Find Large Unused Files
Getting the list of unused files is very useful, as you can readily delete them to save space on your hard disk. Do this with the help of the -mtime flag and the find command discussed earlier. The following instructions will list out the top 10 files, which have not been modified for more than 30 days and have a file size of at least 100MB.
find / -xdev -mtime +30 -type f -size +100M
GUI Apps to Find the Largest Files in Linux
If you are running Linux on your desktop, make use of these GUI apps to find the largest files in your system.
Disk Usage Analyzer
One of the best GUI apps to analyze file sizes in Linux is Disk Usage Analyzer. It comes preinstalled in your Gnome desktop environment.
- If this application is not installed on your machine, you can easily install the disk usage analyzer application like so:
sudo apt update sudo apt install baobab
For Fedora or other red-hat-based distributions, install Disk Usage Analyzer by using the following command:
- Open the app and select the filesystem you want to scan. Disk Usage Analyzer will list the attached filesystem in your machine.
- You’ll have to wait a few seconds until the scan completes.
- Once the process is done, you’ll be able to see the list of files and folders sorted according to their sizes (larger ones at the top, smaller towards the bottom).
Some additional GUI apps that you can use to find large files on your Linux system include:
Remove the Largest Files
After finding the largest files, you need to remove them and can easily do so with the help of the rm command in Linux.
- Copy the absolute or relative file of the file you want to delete, then append the file path after the rm command.
rm "your file path goes here"
- To remove any non-empty directory, use the -rf after the rm command. -r represents recursively deleting the files inside the directory, and -f implies force to delete that directory. For example, if you want to delete your “Downloads” folder along with all the files inside it, run the following command.
Frequently Asked Questions
Why I am getting a «permission denied» error?
If you want to run a command beyond your home directory, you should have root permission. Otherwise, you will get the permission denied error. Try using sudo before the command to elevate your permission as a root user. You can successfully run any command on your system files. Try to be careful when using sudo with commands.
How do I find files larger than 1GB?
To find files larger than 1GB, use the find command with its -size flag. The command will look like this: sudo find / -xdev -type f -size +1G .
How can I view the size of a particular folder?
To see the size of a folder, use any of the tools mentioned in this article. You can also use your File Explorer to see the size of a folder. Just right-click on the folder and select the properties option. There you can easily find the listed folder size.
Image source: Unsplash All screenshots Hrishikesh Pathak
Developer and writer. Write about linux and web.
Our latest tutorials delivered straight to your inbox
How to Find Out Top Directories and Files (Disk Space) in Linux
As a Linux administrator, you must periodically check which files and folders are consuming more disk space. It is very necessary to find unnecessary junk and free up from your hard disk.
This brief tutorial describes how to find the largest files and folders in the Linux file system using du (disk usage) and find command. If you want to learn more about these two commands, then head over to the following articles.
How to Find Biggest Files and Directories in Linux
Run the following command to find out top biggest directories under /home partition.
# du -a /home | sort -n -r | head -n 5
The above command displays the biggest 5 directories of my /home partition.
Find Largest Directories in Linux
If you want to display the biggest directories in the current working directory, run:
Let us break down the command and see what says each parameter.
- du command: Estimate file space usage.
- a : Displays all files and folders.
- sort command : Sort lines of text files.
- -n : Compare according to string numerical value.
- -r : Reverse the result of comparisons.
- head : Output the first part of files.
- -n : Print the first ‘n’ lines. (In our case, We displayed the first 5 lines).
Some of you would like to display the above result in human-readable format. i.e you might want to display the largest files in KB, MB, or GB.
The above command will show the top directories, which are eating up more disk space. If you feel that some directories are not important, you can simply delete a few sub-directories or delete the entire folder to free up some space.
To display the largest folders/files including the sub-directories, run:
Find out the meaning of each option using in above command:
- du command: Estimate file space usage.
- -h : Print sizes in human-readable format (e.g., 10MB).
- -S : Do not include the size of subdirectories.
- -s : Display only a total for each argument.
- sort command : sort lines of text files.
- -r : Reverse the result of comparisons.
- -h : Compare human readable numbers (e.g., 2K, 1G).
- head : Output the first part of files.
Find Out Top File Sizes Only
If you want to display the biggest file sizes only, then run the following command:
# find -type f -exec du -Sh <> + | sort -rh | head -n 5
To find the largest files in a particular location, just include the path beside the find command:
# find /home/tecmint/Downloads/ -type f -exec du -Sh <> + | sort -rh | head -n 5 OR # find /home/tecmint/Downloads/ -type f -printf "%s %p\n" | sort -rn | head -n 5
The above command will display the largest file from /home/tecmint/Downloads directory.
That’s all for now. Finding the biggest files and folders is no big deal. Even a novice administrator can easily find them. If you find this tutorial useful, please share it on your social networks and support TecMint.