Linux find biggest folders

Linux find largest file in directory recursively using find/du

I have 500GB SSD installed on my Linux server. My web server is running out of the disk space. I need to find a biggest or largest file concerning file size on the disk. How do I find largest file in a directory recursively using the find command?

To find a big file concerning file size on disk is easy task if you know how to use the find, du and other command. The du command used to estimate file space usage on Linux system. The output of du passed on to the sort and head command using shell pipes. Let us see how to find largest file in Linux server using various commands.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux
Est. reading time 3 minutes

Linux find largest file in directory recursively using find

The procedure to find largest files including directories in Linux is as follows:

  1. Open the terminal application
  2. Login as root user using the sudo -i command
  3. Type du -a /dir/ | sort -n -r | head -n 20
  4. du will estimate file space usage
  5. sort will sort out the output of du command
  6. head will only show top 20 largest file in /dir/

Linux find a biggest files in /

Linux find large files quickly with bash alias

One can hunt down disk space hogs with ducks bash shell alias

How To Find Largest Top 10 Files and Directories On Linux / UNIX / BSD

Finding largest file recursively on Linux bash shell using find

One can only list files and skip the directories with the find command instead of using the du command, sort command and head command combination:
$ sudo find / -type f -printf «%s\t%p\n» | sort -n | tail -1
$ find $HOME -type f -printf ‘%s %p\n’ | sort -nr | head -10
Here is what I got on my systems:

Where, find command options are as follows:

  • $HOME – Directory search for files.
  • -type f – Search for regular files only.
  • -printf ‘%s %p\n’ – Force find to use print format on the scren, interpreting \ escapes and % directives. The %s will print file’s size in bytes. Show file name using %p . This speailized output makes it easy to sort out file names using the sort command.

The -n is for numeric sort and the -r passed to sort will reverse the result of comparisons. The head command is used to control and show the first part of files. In other words, only display the top 10 results from previous commands.

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Great! I found the largest files on my disk. What next?

Depend upon file/dir type you can either move or delete the file. For example, you cannot remove or move the Linux kernel or diver directories. To delete unwanted file on Linux use the rm command:
rm -i -v /path/to/file
To get rid of all files and its sub-directories recursively use following command:
rm -rf /path/to/folderName
To move file to a usb pen mounted at /mnt/usb/, run the mv command:
mv /path/to/large/file/ /mnt/usb/

Conclusion

You just learned how to search, find and list largest or biggest directories/files in Linux using the combination of du/find and other commands. For more info see this page or man pages of du and find commands:
man du
man find
man sort
man head
man tail

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

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

Find Largest Directories in Linux

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:

Find Biggest Directories Only

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.

Find Top Directories Sizes in Linux

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 Largest Folder and Subdirectories

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 Top File Sizes in Linux

To find the largest files in a particular location, just include the path beside the find command:

Find Top File Size in Specific Location

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.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

How To: Linux Find Large Files in a Directory

H ow do I find out all large files in a directory?

There is no single command that can be used to list all large files. But, with the help of find command command and shell pipes, you can easily list all large files. This page explains how to find the largest files and directories in Linux using various commands.

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements Find and du commands on Linux or Unix
Est. reading time 4 minutes

Linux List All Large Files

To finds all files over 50,000KB (50MB+) in size and display their names, along with size, use following syntax:

The syntax may vary based upon GNU/find and your Linux distro. Hence read man pages.

Syntax for RedHat / CentOS / Fedora Linux

find -type f -size +k -exec ls -lh <> \; | awk ‘< print $9 ": " $5 >‘
Search or find big files Linux (50MB) in current directory, enter:
$ find . -type f -size +50000k -exec ls -lh <> \; | awk ‘< print $9 ": " $5 >‘
Search in my /var/log directory:
# find /var/log -type f -size +100000k -exec ls -lh <> \; | awk ‘< print $9 ": " $5 >‘

Syntax for Debian / Ubuntu Linux

find -type f -size +k -exec ls -lh <> \; | awk ‘< print $8 ": " $5 >‘
Search in current directory:
$ find . -type f -size +10000k -exec ls -lh <> \; | awk ‘< print $8 ": " $5 >‘
Sample output:

Above commands will lists files that are are greater than 10,000 kilobytes in size. To list all files in your home directory tree less than 500 bytes in size, type:
$ find $HOME -size -500b
OR
$ find

-size -500b
To list all files on the system whose size is exactly 20 512-byte blocks, type:
# find / -size 20

Finding large files using the find command

Let us search for files with size greater than 1000 MB, run

Источник

Поиск больших файлов Linux

Если на вашем жёстком диске закончилось свободное пространство, самый простой способ его освободить — найти и удалить самые большие и при этом ненужные файлы. Такая задача может возникнуть как на сервере, так и на домашнем компьютере, поэтому существуют удобные решения для обоих ситуаций. Способов поиска больших файлов существует очень много.

Как вы уже поняли, в этой небольшой инструкции мы рассмотрим, как найти большие файлы Linux с помощью графического интерфейса или консольных утилит. Будем двигаться от самого простого к более сложному.

Поиск больших файлов Linux

1. GDMap

Несмотря на то, что графических утилит есть около десятка, все они мне не очень нравятся. Например в Gnome можно использовать GDMap, а в KDE — fileslight. Обе утилиты сканируют файловую систему и выводят все файлы в виде диаграммы. Размер блока зависит от размера файла. Чем больше файл или папка, тем больше блок. Для установки GDMap в Ubuntu выполните:

sudo apt install gdmap

Затем запустите утилиту из главного меню. По умолчанию она отображает домашнюю папку. Здесь можно оценить, какие файлы самые увесистые.

2. Утилита ncdu

Это псевдографическая утилита, которая работает в терминале Linux. Она отображает список файлов и директорий по объёму и, что самое интересное, тут же позволяет удалять ненужные файлы. Для установки утилиты выполните:

sudo apt install ncdu

Затем запустите утилиту, передав ей в качестве параметра папку, которую надо просканировать. Можно проверить ту же домашнюю папку:

У утилиты очень простое управление. Для перемещения по списку используйте кнопки со стрелками вверх и вниз, для открытия папки — клавишу 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.

Источник

Читайте также:  Восстановление удаленного файла mac os
Оцените статью