Show biggest files linux

Поиск больших файлов 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.

Читайте также:  Create tcp server linux

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

How to Find Large Files in Linux

Largest File

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.

  1. To see more information about files and directories including their permissions, you can use the -l flag.

Largest File 1

  1. To print their size along with all of the information, use the -s flag along with the previous -l flag.

Largest File 3

  1. By default, the ls command will only list the directories. To see the files inside the directories recursively, use the -R flag.

Largest File 4

  1. 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:

Largest File 5

Largest File 6

  1. 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.

Largest File 7

  1. 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.

Largest File 8

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.

Largest File 12

Largest File 10

find ./test -type f -size +100M
  1. Doing so will find all the files inside the “test” directory which has a size greater than 100MB.
  2. 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.

  1. 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.

Largest File 13

  1. 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.
Читайте также:  Удалить драйвера нвидиа линукс

Largest File 15 1

  1. 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.

Largest File 17

  1. 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

Largest File 18

  1. 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.

  1. 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:

  1. Open the app and select the filesystem you want to scan. Disk Usage Analyzer will list the attached filesystem in your machine.
  2. You’ll have to wait a few seconds until the scan completes.
  3. 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).

Largest File 19

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.

  1. 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"
  1. 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 .

Читайте также:  Using at linux command line

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.

  1. du command: Estimate file space usage.
  2. a : Displays all files and folders.
  3. sort command : Sort lines of text files.
  4. -n : Compare according to string numerical value.
  5. -r : Reverse the result of comparisons.
  6. head : Output the first part of files.
  7. -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:

  1. du command: Estimate file space usage.
  2. -h : Print sizes in human-readable format (e.g., 10MB).
  3. -S : Do not include the size of subdirectories.
  4. -s : Display only a total for each argument.
  5. sort command : sort lines of text files.
  6. -r : Reverse the result of comparisons.
  7. -h : Compare human readable numbers (e.g., 2K, 1G).
  8. 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.

Источник

Оцените статью
Adblock
detector