Как найти файлы большого размера linux

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

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

1. GDMap

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

sudo apt install gdmap

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

2. Утилита ncdu

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

sudo apt install ncdu

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

ncdu /home

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

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

We’re just starting a UNIX class and are learning a variety of Bash commands. Our assignment involves performing various commands on a directory that has a number of folders under it as well.

I know how to list and count all the regular files from the root folder using:

find . -type l | wc -l

But I’d like to know where to go from there in order to find the largest file in the whole directory. I’ve seen somethings regarding a du command, but we haven’t learned that, so in the repertoire of things we’ve learned I assume we need to somehow connect it to the ls -t command.

And pardon me if my ‘lingo’ isn’t correct, I’m still getting used to it!

jww's user avatar

jww

96.5k90 gold badges407 silver badges878 bronze badges

asked Sep 20, 2012 at 23:15

Rekson's user avatar

2

Quote from this link-

If you want to find and print the top 10 largest files names (not
directories) in a particular directory and its sub directories

$ find . -type f -printf '%s %pn'|sort -nr|head

To restrict the search to the present directory use «-maxdepth 1» with
find.

$ find . -maxdepth 1 -printf '%s %pn'|sort -nr|head

And to print the top 10 largest «files and directories»:

$ du -a . | sort -nr | head

** Use «head -n X» instead of the only «head» above to print the top X largest files (in all the above examples)

user2297550's user avatar

user2297550

3,0922 gold badges27 silver badges39 bronze badges

answered Sep 20, 2012 at 23:21

tamsler's user avatar

tamslertamsler

1,2651 gold badge18 silver badges26 bronze badges

10

To find the top 25 files in the current directory and its subdirectories:

find . -type f -exec ls -al {} ; | sort -nr -k5 | head -n 25

This will output the top 25 files by sorting based on the size of the files via the «sort -nr -k5» piped command.

Same but with human-readable file sizes:

find . -type f -exec ls -alh {} ; | sort -hr -k5 | head -n 25

murla's user avatar

murla

952 silver badges10 bronze badges

answered May 29, 2014 at 3:42

xpros's user avatar

xprosxpros

2,10618 silver badges15 bronze badges

0

find . -type f | xargs ls -lS | head -n 1

outputs

-rw-r--r--  1 nneonneo  staff  9274991 Apr 11 02:29 ./devel/misc/test.out

If you just want the filename:

find . -type f | xargs ls -1S | head -n 1

This avoids using awk and allows you to use whatever flags you want in ls.

Caveat. Because xargs tries to avoid building overlong command lines, this might fail if you run it on a directory with a lot of files because ls ends up executing more than once. It’s not an insurmountable problem (you can collect the head -n 1 output from each ls invocation, and run ls -S again, looping until you have a single file), but it does mar this approach somewhat.

answered Sep 21, 2012 at 3:45

nneonneo's user avatar

nneonneonneonneo

170k35 gold badges306 silver badges377 bronze badges

3

There is no simple command available to find out the largest files/directories on a Linux/UNIX/BSD filesystem. However, combination of following three commands (using pipes) you can easily find out list of largest files:

# du -a /var | sort -n -r | head -n 10

If you want more human readable output try:

$ cd /path/to/some/var
$ du -hsx * | sort -rh | head -10

Where,

  • Var is the directory you wan to search
  • du command -h option : display sizes in human readable format (e.g.,
    1K, 234M, 2G).
  • du command -s option : show only a total for each
    argument (summary).
  • du command -x option : skip directories on
    different file systems.
  • sort command -r option : reverse the result
    of comparisons.
  • sort command -h option : compare human readable
    numbers. This is GNU sort specific option only.
  • head command -10 OR -n 10 option : show the first 10 lines.

answered May 26, 2014 at 9:34

Kalpana's user avatar

KalpanaKalpana

4911 gold badge7 silver badges21 bronze badges

2

This lists files recursively if they’re normal files, sorts by the 7th field (which is size in my find output; check yours), and shows just the first file.

find . -type f -ls | sort +7 | head -1

The first option to find is the start path for the recursive search. A -type of f searches for normal files. Note that if you try to parse this as a filename, you may fail if the filename contains spaces, newlines or other special characters. The options to sort also vary by operating system. I’m using FreeBSD.

A «better» but more complex and heavier solution would be to have find traverse the directories, but perhaps use stat to get the details about the file, then perhaps use awk to find the largest size. Note that the output of stat also depends on your operating system.

answered Sep 20, 2012 at 23:20

ghoti's user avatar

ghotighoti

45.1k8 gold badges65 silver badges104 bronze badges

7

This will find the largest file or folder in your present working directory:

ls -S /path/to/folder | head -1

To find the largest file in all sub-directories:

find /path/to/folder -type f -exec ls -s {} ; | sort -nr | awk 'NR==1 { $1=""; sub(/^ /, ""); print }'

answered Sep 20, 2012 at 23:21

Steve's user avatar

SteveSteve

49.9k13 gold badges89 silver badges102 bronze badges

2

On Solaris I use:

find . -type f -ls|sort -nr -k7|awk 'NR==1{print $7,$11}' #formatted

or

find . -type f -ls | sort -nrk7 | head -1 #unformatted

because anything else posted here didn’t work.
This will find the largest file in $PWD and subdirectories.

answered Oct 13, 2013 at 22:33

rindeal's user avatar

rindealrindeal

99311 silver badges16 bronze badges

0

Try the following one-liner (display top-20 biggest files):

ls -1Rs | sed -e "s/^ *//" | grep "^[0-9]" | sort -nr | head -n20

or (human readable sizes):

ls -1Rhs | sed -e "s/^ *//" | grep "^[0-9]" | sort -hr | head -n20

Works fine under Linux/BSD/OSX in comparison to other answers, as find’s -printf option doesn’t exist on OSX/BSD and stat has different parameters depending on OS. However the second command to work on OSX/BSD properly (as sort doesn’t have -h), install sort from coreutils or remove -h from ls and use sort -nr instead.

So these aliases are useful to have in your rc files:

alias big='du -ah . | sort -rh | head -20'
alias big-files='ls -1Rhs | sed -e "s/^ *//" | grep "^[0-9]" | sort -hr | head -n20'

answered Mar 5, 2015 at 12:34

kenorb's user avatar

kenorbkenorb

153k85 gold badges674 silver badges738 bronze badges

2

Try following command :

find /your/path -printf "%k %pn" | sort -g -k 1,1 | awk '{if($1 > 500000) print $1/1024 "MB" " " $2 }' |tail -n 1 

This will print the largest file name and size and more than 500M. You can move the if($1 > 500000),and it will print the largest file in the directory.

Jad Chahine's user avatar

Jad Chahine

6,6998 gold badges37 silver badges59 bronze badges

answered Sep 21, 2012 at 3:23

zjhui's user avatar

zjhuizjhui

7691 gold badge8 silver badges21 bronze badges

du -aS /PATH/TO/folder | sort -rn | head -2 | tail -1

or

du -aS /PATH/TO/folder | sort -rn | awk 'NR==2'

answered Sep 20, 2012 at 23:33

Ansgar Wiechers's user avatar

Ansgar WiechersAnsgar Wiechers

191k23 gold badges245 silver badges321 bronze badges

To list the larger file in a folder

ls -sh /pathFolder | sort -rh | head -n 1

The output of ls -sh is a sized s and human h understandable view of the file size number.

You could use ls -shS /pathFolder | head -n 1. The bigger S from ls already order the list from the larger files to the smaller ones but the first result its the sum of all files in that folder. So if you want just to list the bigger file, one file, you need to head -n 2 and check at the «second line result» or use the first example with ls sort head.

answered Mar 8, 2018 at 1:14

José Pacheco's user avatar

This command works for me,

find /path/to/dir -type f -exec du -h '{}' + | sort -hr | head -10

Lists Top 10 files ordered by size in human-readable mode.

answered Jul 26, 2021 at 19:07

AATHITH RAJENDRAN's user avatar

This script simplifies finding largest files for further action.
I keep it in my ~/bin directory, and put ~/bin in my $PATH.

#!/usr/bin/env bash
# scriptname: above
# author: Jonathan D. Lettvin, 201401220235

# This finds files of size >= $1 (format ${count}[K|M|G|T], default 10G)
# using a reliable version-independent bash hash to relax find's -size syntax.
# Specifying size using 'T' for Terabytes is supported.
# Output size has units (K|M|G|T) in the left hand output column.

# Example:
#   ubuntu12.04$ above 1T
#   128T /proc/core

# http://stackoverflow.com/questions/1494178/how-to-define-hash-tables-in-bash
# Inspiration for hasch: thanks Adam Katz, Oct 18 2012 00:39
function hasch() { local hasch=`echo "$1" | cksum`; echo "${hasch//[!0-9]}"; }
function usage() { echo "Usage: $0 [{count}{k|K|m|M|g|G|t|T}"; exit 1; }
function arg1() {
    # Translate single arg (if present) into format usable by find.
    count=10; units=G;  # Default find -size argument to 10G.
    size=${count}${units}
    if [ -n "$1" ]; then
        for P in TT tT GG gG MM mM Kk kk; do xlat[`hasch ${P:0:1}`]="${P:1:1}"; done
        units=${xlat[`hasch ${1:(-1)}`]}; count=${1:0:(-1)}
        test -n "$units" || usage
        test -x $(echo "$count" | sed s/[0-9]//g) || usage
        if [ "$units" == "T" ]; then units="G"; let count=$count*1024; fi
        size=${count}${units}
    fi
}
function main() {
    sudo 
        find / -type f -size +$size -exec ls -lh {} ; 2>/dev/null | 
        awk '{ N=$5; fn=$9; for(i=10;i<=NF;i++){fn=fn" "$i};print N " " fn }'
}

arg1 $1
main $size

answered Jan 22, 2014 at 7:41

jlettvin's user avatar

jlettvinjlettvin

1,1017 silver badges13 bronze badges

That is quite simpler way to do it:

ls -l | tr -s " " " " | cut -d " " -f 5,9 | sort -n -r | head -n 1***

And you’ll get this: 8445 examples.desktop

Daniel Serodio's user avatar

answered Mar 14, 2014 at 7:40

Andrii Kovalchuk's user avatar

Andrii KovalchukAndrii Kovalchuk

4,2332 gold badges35 silver badges31 bronze badges

1

Linux Solution: For example, you want to see all files/folder list of your home (/) directory according to file/folder size (Descending order).

sudo du -xm / | sort -rn | more

answered Mar 3, 2017 at 21:05

Monir's user avatar

MonirMonir

1,36213 silver badges16 bronze badges

ls -alR|awk '{ if ($5 > max) {max=$5;ff=$9}} END {print max "t" ff;}'

answered Jan 11, 2019 at 16:34

Borislav Markov's user avatar

Kindly run below one liner with your required-path. as of now i am running for /var/log/ location

 (sudo  du -a /var/log/ |sort -nr|head -n20 |awk '{print $NF}'|while read l ;do du -csh $l|grep -vi total;done ) 2> /dev/null

answered Oct 27, 2022 at 15:31

linux.cnf's user avatar

linux.cnflinux.cnf

4936 silver badges7 bronze badges

Время на прочтение
5 мин

Количество просмотров 125K

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

Команда find – это невероятно мощный инструмент, позволяющий искать файлы не только по названию, но и по:

  • Дате добавления.
  • Содержимому.
  • Регулярным выражениям.

Данная команда будет очень полезна системным администраторам для:

  • Управления дисковым пространством.
  • Бэкапа.
  • Различных операций с файлами.

Команда find в Linux производит поиск файлов и папок на основе заданных вами критериев и позволяет выполнять действия с результатами поиска.

Синтаксис команды find:

$ find directory-to-search criteria action

Где:

  • directory-to-search (каталог поиска) – это отправной каталог, с которой find начинает поиск файлов по всем подкаталогам, которые находятся внутри. Если не указать путь, тогда поиск начнется в текущем каталоге;
  • criteria (критерий) – критерий, по которым нужно искать файлы;
  • action (действие) – что делать с каждым найденным файлом, соответствующим критериям.

Поиск по имени

Следующая команда ищет файл s.txt в текущем каталоге:

$ find . -name "s.txt"
./s.txt

Где:

  • . (точка) – файл относится к нынешнему каталогу
  • -name – критерии по которым осуществляется поиск. В данном случае поиск по названию файла.

В данном случае критерий -name учитывает только символы нижнего регистра и файл S.txt не появиться в результатах поиска. Чтобы убрать чувствительность к регистру необходимо использовать –iname.

$ find . -iname "s.txt"
./s.txt
./S.txt

Для поиска всех изображений c расширением .png нужно использовать шаблон подстановки *.png:

$ find . -name "*.png"
./babutafb.png
./babutafacebook.png
./Moodle2.png
./moodle.png
./moodle/moodle1.png
./genxfacebook.png

Можно использовать название каталога для поиска. Например, чтобы с помощью команды find найти все png изображения в каталоге home:

$ find /home -name "*.png"
find: `/home/babuta/.ssh': Permission denied
/home/vagrant/Moodle2.png
/home/vagrant/moodle.png
/home/tisha/hello.png
find: `/home/tisha/testfiles': Permission denied
find: `/home/tisha/data': Permission denied
/home/tisha/water.png
find: `/home/tisha/.cache': Permission denied

Если выдает слишком много ошибок в отказе разрешения, тогда можно добавить в конец команды – 2> /dev/null. Таким образом сообщения об ошибках будут перенаправляться по пути dev/null, что обеспечит более чистую выдачу.

find /home -name "*.jpg" 2>/dev/null
/home/vagrant/Moodle2.jpg
/home/vagrant/moodle.jpg
/home/tisha/hello.jpg
/home/tisha/water.jpg

Поиск по типу файла

Критерий -type позволяет искать файлы по типу, которые бывают следующих видов:

  • f – простые файлы;
  • d – каталоги;
  • l – символические ссылки;
  • b – блочные устройства (dev);
  • c – символьные устройства (dev);
  • p – именованные каналы;
  • s – сокеты;

Например, указав критерий -type d будут перечислены только каталоги:

$ find . -type d
.
./.ssh
./.cache
./moodle

Поиск по размеру файла

Допустим, что вам необходимо найти все большие файлы. Для таких ситуаций подойдет критерий -size.

  • «+» — Поиск файлов больше заданного размера
  • «-» — Поиск файлов меньше заданного размера
  • Отсутствие знака означает, что размер файлов в поиске должен полностью совпадать.

В данном случае поиск выведет все файлы более 1 Гб (+1G).

$ find . -size +1G
./Microsoft_Office_16.29.19090802_Installer.pkg
./android-studio-ide-183.5692245-mac.dmg

Единицы измерения файлов:

  • c — Байт
  • k — Кбайт
  • M — Мбайт
  • G — Гбайт

Поиск пустых файлов и каталогов

Критерий -empty позволяет найти пустые файлы и каталоги.

$ find . -empty
./.cloud-locale-test.skip
./datafiles
./b.txt
...
./.cache/motd.legal-displayed

Поиск времени изменения

Критерий -cmin позволяет искать файлы и каталоги по времени изменения. Для поиска всех файлов, измененных за последний час (менее 60 мин), нужно использовать -60:

$ find . -cmin -60
.
./a.txt
./datafiles

Таким образом можно найти все файлы в текущем каталоге, которые были созданы или изменены в течение часа (менее 60 минут).

Для поиска файлов, которые наоборот были изменены в любое время кроме последнего часа необходимо использовать +60.

$ find . -cmin +60

Поиск по времени доступа

Критерий -atime позволяет искать файлы по времени последнего доступа.

$ find . -atime +180

Таким образом можно найти файлы, к которым не обращались последние полгода (180 дней).

Поиск по имени пользователя

Опция –user username дает возможность поиска всех файлов и каталогов, принадлежащих конкретному пользователю:

$ find /home -user tisha 2>/dev/null

Таким образом можно найти все файлы пользователя tisha в каталоге home, а 2>/dev/null сделает выдачу чистой без ошибок в отказе доступа.

Поиск по набору разрешений

Критерий -perm – ищет файлы по определенному набору разрешений.

$ find /home -perm 777

Поиск файлов с разрешениями 777.

Операторы

Для объединения нескольких критериев в одну команду поиска можно применять операторы:

  • -and
  • -or
  • -not

Например, чтобы найти файлы размером более 1 Гбайта пользователя tisha необходимо ввести следующую команду:

$ find /home  -user tisha  -and  -size +1G  2>/dev/null

Если файлы могут принадлежать не только пользователю tisha, но и пользователю pokeristo, а также быть размером более 1 Гбайта.

$ find /home ( -user pokeristo -or -user tisha )  -and  -size +1G  2>/dev/null

Перед скобками нужно поставить обратный слеш «».

Действия

К команде find можно добавить действия, которые будут произведены с результатами поиска.

  • -delete — Удаляет соответствующие результатам поиска файлы
  • -ls — Вывод более подробных результатов поиска с:
    • Размерами файлов.
    • Количеством inode.
  • -print Стоит по умолчанию, если не указать другое действие. Показывает полный путь к найденным файлам.
  • -exec Выполняет указанную команду в каждой строке результатов поиска.

-delete

Полезен, когда необходимо найти и удалить все пустые файлы, например:

$ find . -empty -delete

Перед удалением лучше лишний раз себя подстраховать. Для этого можно запустить команду с действием по умолчанию -print.

-exec:

Данное действие является особенным и позволяет выполнить команду по вашему усмотрению в результатах поиска.

-exec command {} ;

Где:

  • command – это команда, которую вы желаете выполнить для результатов поиска. Например:
    • rm
    • mv
    • cp
  • {} – является результатами поиска.
  • ; — Команда заканчивается точкой с запятой после обратного слеша.

С помощью –exec можно написать альтернативу команде –delete и применить ее к результатам поиска:

$ find . -empty -exec rm {} ;

Другой пример использования действия -exec:

$ find . -name "*.jpg" -exec cp {} /backups/fotos ;

Таким образом можно скопировать все .jpg изображения в каталог backups/fotos

Заключение

Команду find можно использовать для поиска:

  • Файлов по имени.
  • Дате последнего доступа.
  • Дате последнего изменения.
  • Имени пользователя (владельца файла).
  • Имени группы.
  • Размеру.
  • Разрешению.
  • Другим критериям.

С полученными результатами можно сразу выполнять различные действия, такие как:

  • Удаление.
  • Копирование.
  • Перемещение в другой каталог.

Команда find может сильно облегчить жизнь системному администратору, а лучший способ овладеть ей – больше практиковаться.

image

Looking for a series of commands that will show me the largest files on a drive.

Andrea Corbellini's user avatar

asked Apr 20, 2011 at 14:01

Ryan Detzel's user avatar

7

If you just need to find large files, you can use find with the -size option. The next command will list all files larger than 10MiB (not to be confused with 10MB):

find / -size +10M -ls

If you want to find files between a certain size, you can combine it with a «size lower than» search. The next command find files between 10MiB and 12MiB:

find / -size +10M -size -12M -ls

apt-cache search 'disk usage' lists some programs available for disk usage analysis. One application that looks very promising is gt5.

From the package description:

Years have passed and disks have become larger and larger, but even on this incredibly huge harddisk era, the space seems to disappear over time. This small and effective programs provides more convenient listing than the default du(1). It displays what has happened since last run and displays dir size and the total percentage. It is possible to navigate and ascend to directories by using cursor-keys with text based browser (links, elinks, lynx etc.)

Screenshot of gt5

On the «related packages» section of gt5, I found ncdu. From its package description:

Ncdu is a ncurses-based du viewer. It provides a fast and easy-to-use interface through famous du utility. It allows to browse through the directories and show percentages of disk usage with ncurses library.

Screenshot of ncdu

Community's user avatar

answered Apr 20, 2011 at 14:16

Lekensteyn's user avatar

LekensteynLekensteyn

171k64 gold badges309 silver badges400 bronze badges

7

My favorite solution uses a mix from several of these good answers.

du -aBM 2>/dev/null | sort -nr | head -n 50 | more

du arguments:

  • -a for «all» files and directories. Leave it off for just directories
  • -BM to output the sizes in megabyte (M) block sizes (B)
  • 2>/dev/null — exclude «permission denied» error messages (thanks @Oli)

sort arguments:

  • -n for «numeric»
  • -r for «reverse» (biggest to smallest)

head arguments:

  • -n 50 for the just top 50 results.
  • Leave off more if using a smaller number

Note: Prefix with sudo to include directories that your account does not have permission to access.

Example showing top 10 biggest files and directories in /var (including grand total).

cd /var
sudo du -aBM 2>/dev/null | sort -nr | head -n 10
7555M   .
6794M   ./lib
5902M   ./lib/mysql
3987M   ./lib/mysql/my_database_dir
1825M   ./lib/mysql/my_database_dir/a_big_table.ibd
997M    ./lib/mysql/my_database_dir/another_big_table.ibd
657M    ./log
629M    ./log/apache2
587M    ./log/apache2/ssl_access.log
273M    ./cache

answered Jul 3, 2015 at 23:24

Dan King's user avatar

Dan KingDan King

7716 silver badges6 bronze badges

1

I just use a combination of du and sort.

sudo du -sx /* 2>/dev/null | sort -n

0   /cdrom
0   /initrd.img
0   /lib64
0   /proc
0   /sys
0   /vmlinuz
4   /lost+found
4   /mnt
4   /nonexistent
4   /selinux
8   /export
36  /media
56  /scratchbox
200 /srv
804 /dev
4884    /root
8052    /bin
8600    /tmp
9136    /sbin
11888   /lib32
23100   /etc
66480   /boot
501072  /web
514516  /lib
984492  /opt
3503984 /var
7956192 /usr
74235656    /home

Then it’s a case of rinse and repeat. Target the subdirectories you think are too big, run the command for them and you find out what’s causing the problem.

Note: I use du‘s -x flag to keep things limited to one filesystem (I have quite a complicated arrangement of cross-mounted things between SSD and RAID5).

Note 2: 2>/dev/null redirects any error messages into oblivion. If they don’t bother you, it’s not obligatory.

answered Apr 20, 2011 at 14:30

Oli's user avatar

OliOli

288k117 gold badges677 silver badges832 bronze badges

1

To display the biggest top-20 directories (recursively) in the current folder, use the following one-liner:

du -ah . | sort -rh | head -20

or (more Unix oriented):

du -a . | sort -rn | head -20

For the top-20 biggest files in the current directory (recursively):

ls -1Rs | sed -e "s/^ *//" | grep "^[0-9]" | sort -nr | head -n20

or with human readable sizes:

ls -1Rhs | sed -e "s/^ *//" | grep "^[0-9]" | sort -hr | head -n20

Please note that -h is available for GNU sort only, so to make it work on OSX/BSD properly, you’ve to install it from coreutils. Then add its folder into your PATH.

So these aliases are useful to have in your rc files (every time when you need it):

alias big='du -ah . | sort -rh | head -20'
alias big-files='ls -1Rhs | sed -e "s/^ *//" | grep "^[0-9]" | sort -hr | head -n20'

answered Mar 5, 2015 at 14:17

kenorb's user avatar

kenorbkenorb

9,8362 gold badges76 silver badges90 bronze badges

qbi’s answer is correct but it will be very slow when there are a lot of files since it will start a new ls process for each item.

a much faster version using find without spawning child processes would be to use printf to print the size in bytes (%s) and the path (%p)

find "$directory" -type f -printf "%s - %pn" | sort -n | tail -n $num_entries

answered Nov 16, 2011 at 12:55

kon's user avatar

konkon

2012 silver badges3 bronze badges

1

This seems like the perfect application for find:

find $DIRECTORY -type f -exec ls -s {} ; | sort -n | tail -n 5

This command will find all files in directory $DIRECTORY and execute ls -s on them. The last command prints the allocated size of a file plus the filename. The result is sorted numerically and and the last five entries are shown. So as result you’ll see the largest 5 files in $DIRETORY or any subdirectory. If you enter tail -n 1 you’ll see only the largest file.

Furthermore you can play around a lot with find. For instance you can look for files which are younger than n days (-ctime -n) or which belong to special users (-user johndoe).

answered Apr 20, 2011 at 14:26

qbi's user avatar

qbiqbi

18.8k9 gold badges78 silver badges127 bronze badges

A great, user-friendly tool referenced in the answer to a similar question is NCurses Disk Usage tool:

sudo ncdu /

answered Sep 9, 2019 at 23:26

janoside's user avatar

janosidejanoside

1,0931 gold badge10 silver badges9 bronze badges

1

When I need make more free space on servers I use this command. It find all files bigger then 50 MB and «du -h» make better list of files and «sort -n» after pipe make list numericcaly sorted by file size.

find / -size +50M -type f -exec du -h {} ; | sort -n

answered Oct 11, 2014 at 20:40

zorbon.cz's user avatar

zorbon.czzorbon.cz

1,14712 silver badges17 bronze badges

Try Baobab, it gives you a graphical overview of files and folders, you can see where the real space hogs are and delete them with one click
https://help.ubuntu.com/community/Baobab

answered Jan 29, 2013 at 11:47

Oliver Hoffmann's user avatar

2

To find all GB files for instance I would use du and grep, though the other methods mentioned here seem great as well.

du -h -a /dir | grep "[0-9]Gb"  

You can also get fancy with the —except option that du has.

muru's user avatar

muru

191k52 gold badges467 silver badges718 bronze badges

answered Jun 11, 2013 at 19:04

dermen's user avatar

dermendermen

1594 bronze badges

You could also sort files by size:

find . -type f -exec du -h {} ; | sort -k1 -h

It finds only files and executes du -h for every file, which shows the size of the file. Lastly, we sort the output of find/du according to the first column (in human readable format).

The last printed file is the largest one.

answered Sep 8, 2016 at 12:28

ABu's user avatar

ABuABu

2354 silver badges13 bronze badges

You can use the command to see the largest files while skipping the directories:

sudo find / -type f -printf “%st%pn” | sort -n | tail -1
find $HOME -type f -printf ‘%s %pn’ | sort -nr | head -10

To find all files that are larger than 100MiB (this is not 100MB, see here if you are confused):

find / -size +100M -ls

the command below will display the largest 5 files in the folder $DIRECTORY:

find $DIRECTORY -type f -exec ls -s {} ; | sort -n | tail -n 5

USING du :
The command below which uses du, display the directories with the 20 largest sizes in the home working folder:

sudo du -a /home | sort -n -r | head -n 20

Now in order now to display the largest directories/files including sub-folders, run:

du -Sh | sort -rh | head -n 10

Using ls:

To list the 5 top largest files in the /bin directory , issue the command below:

ls -lSh /bin | head -5

You can also use the Disk Usage Analyzer or Baobao as shown here for example.

Kulfy's user avatar

Kulfy

17.3k26 gold badges63 silver badges102 bronze badges

answered Aug 27, 2019 at 16:32

Zezo's user avatar

Finding the largest files is extremely useful especially when you you’re low on disk space and want to free it up.

The best way to find the largest files on your Linux system is to use the command line.

Actually there is no simple command to list the largest files in Linux.

However, you can easily find the largest files, using a combination of the several simple commands.

Find The Largest Files in Linux

Run the combination of the following commands to find the largest files on your Linux system, beginning from the <DIR> directory (change <DIR> to whatever directory you need), and list top 10 of them.

$ find <DIR> -mount -type f -ls 2> /dev/null | sort -rnk7 | head -10 | awk '{printf "%10d MBt%sn",($7/1024)/1024,$NF}'

Find 10 largest files, starting from ‘/’ (root)

$ find / -mount -type f -ls 2> /dev/null | sort -rnk7 | head -10 | awk '{printf "%10d MBt%sn",($7/1024)/1024,$NF}'

       106 MB	/var/lib/mysql/ibdata1
        94 MB	/usr/lib/locale/locale-archive
        41 MB	/scripts/20130206-015833.tar.gz
        41 MB	/scripts/20130206-004839.tar.gz
        41 MB	/scripts/20130206-130400.tar.gz
        41 MB	/scripts/20130206-000442.tar.gz
        41 MB	/scripts/20130206-132019.tar.gz
        41 MB	/root/20130208-133954.tar.gz
        33 MB	/var/log/messages-20130303
        32 MB	/var/lib/rpm/Packages

Find 10 largest files, starting from ‘/home’

$ find /home -mount -type f -ls 2> /dev/null | sort -rnk7 | head -10 | awk '{printf "%10d MBt%sn",($7/1024)/1024,$NF}'

      3007 MB	/home/user/Desktop/share/linux-65835.iso
       448 MB	/home/user/Pictures/Turkey/SAM_4590.AVI
       266 MB	/home/user/Pictures/Turkey/SAM_4588.AVI
       173 MB	/home/user/Camera/VID_20130909_120713.mp4
       152 MB	/home/user/Camera/VID_20130909_115427.mp4
       133 MB	/home/user/Camera/VID_20130909_210904.mp4
       133 MB	/home/user/Pictures/Paris/VID_20130928_182431.mp4
       131 MB	/home/user/Pictures/Turkey/SAM_4597.AVI
       129 MB	/home/user/Pictures/Turkey/SAM_4641.AVI
       127 MB	/home/user/Desktop/tmp/Camera/VID_20130911_164440.mp4

Was it useful? Share this post with the world!

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти площадь боковой поверхности пирамиды шестиугольной
  • Как найти как делают игрушки
  • Принтер стал печатать синим цветом как исправить
  • Как найти код пикселя на facebook
  • Как найти где контейнер по номеру

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии