Linux найти файлы больше 1гб

Linux: Find files larger than given size (gb/mb/kb/bytes)

In this article, we will discuss how to recursively find files which are larger than a given size in Linux, using the find command.

Table of Contents

Many times we encounter a situation where we need to find huge files in Linux. These files can be log files or some other kind of data files. In such scenarios we need to search files by size. For this, we can easily use the find command in Linux.

The find command in Linux provides an easy way to search files recursively in a directory hierarchy. It also provides various options to do the selective search. One such option is “-size”, it helps to recursively search files by size.

Syntax of find command to find files bigger than given size in Linux

In the given , it will recursively search for the files whose size is greater than N. Here N is a number and along with it we can specify size unit type like,

Frequently Asked:

For example, “-size +4G” makes the find command to search for files greater than 4GB. Here, + sign is denote that look for files greater than or equal to N[Type], like in this case, -size +4G will make find command to look for files bigger than 4GB.

Let’s see some detailed examples of finding files greater than a given size,

Find files larger than 4gb in Linux

To find files larger than 4GB, we need to pass the -size option with value +4G in the find command.

/usr/logs/test_1_logs.txt /usr/logs/test_2_logs.txt

It recursively searched for files inside the folder “/usr” and filtered out the files with size larger than or equal to 4GB, then printed the paths of such files.

The previous command just printed the file paths which are greater than 4GB. If you want print the size along with file name then use this command,

find /usr -type f -size +4G -exec ls -lh <> \; | awk '< print $9 "|| Size : " $5 >'
/usr/logs/test_1_logs.txt|| Size : 4.6G /usr/logs/test_2_logs.txt|| Size : 7.2G

Find files larger than 1gb in Linux

To find files larger than 1GB, we need to pass the -size option with value +1G in the find command.

/usr/logs/error_logs.txt
/usr/logs/warning_logs.txt

It recursively searched for files inside the folder “/usr/” and filtered out the files with size larger than or equal to 1GB, then printed the paths of such files.

Читайте также:  Linux boot repair iso

The previous command just printed the file paths which are greater than 1GB. If you want print the size along with file name then use this command,

find /usr -type f -size +1G -exec ls -lh <> \; | awk '< print $9 "|| Size : " $5 >'
/usr/logs/error_logs.txt|| Size : 1.6G /usr/logs/warning_logs.txt|| Size : 2.2G

Find files larger than 500mb in Linux

To find files larger than 500 MB, we need to pass the -size option with value +500M in the find command.

find /usr -type f -size +500M

It will recursively search for the files inside the folder “/usr/” and filter out the files with size larger than or equal to 500MB, then print the paths of each such files.

/usr/logs/test_3_logs.txt /usr/logs/test_4_logs.txt

To print file size along with with file paths for files larger than 500MB use this command,

find /usr -type f -size +500M -exec ls -lh <> \; | awk '< print $9 "|| Size : " $5 >'

It will print the file paths along with size for the files larger than 500MB.

/usr/logs/test_3_logs.txt|| Size : 610G /usr/logs/test_4_logs.txt|| Size : 712G

Find files larger than 100mb in Linux

To find files larger than 100 MB, we need to pass the -size option with value +100M in the find command.

find /usr -type f -size +100M

It will recursively search for the files inside the folder “/usr/” and filter out the files with size larger than or equal to 100MB, then print the paths of each such files. To print file size along with with file paths for files larger than 100MB use this command,

find /usr -type f -size +100M -exec ls -lh <> \; | awk '< print $9 "|| Size : " $5 >'

It will print the file paths along with size for the files larger than 100MB.

Find files larger than 50mb in Linux

To find files larger than 50 MB, we need to pass the -size option with value +50M in the find command.

It will recursively search for the files inside the folder “/usr/” and filter out the files with size larger than or equal to 50MB, then print the paths of each such files. To print file size along with with file paths for files larger than 50MB use this command,

find /usr -type f -size +50M -exec ls -lh <> \; | awk '< print $9 "|| Size : " $5 >'

It will print the file paths along with size for the files larger than 50MB.

Find files larger than 0 bytes in Linux

To find files larger than 0 Bytes, we need to pass the -size option with value +0b in the find command.

Читайте также:  Change user on linux command

It will recursively search for the files inside the folder “/usr/” and filter out the files with size larger than or equal to 0 Bytes, then print the paths of each such files. To print file size along with with file paths for files larger than 0 Bytes use this command,

find /usr -type f -size +0b -exec ls -lh <> \; | awk '< print $9 "|| Size : " $5 >'

It will print the file paths along with size for the files larger than 0 bytes.

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Поиск больших файлов и директорий в Linux

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

Дисковое пространство не вечно. Рано или поздно приходит момент, когда его катастрофически не хватает. Эффективный способ это исправить — найти файлы и директории, которые занимают больше всего места.

Рассмотрим, как это сделать в Linux с использованием команд find и du .

Поиск больших файлов командой find

Простой поиск

Команда find имеет опцию -size , которая позволяет указать размер файлов для поиска.

Найдем файлы, которые занимают больше 1Gb:

find . -mount -type f -size +1G 2>/dev/null
  • Символ точка . после самой команды find, означает, что поиск нужно вести в текущей директории. Вместо точки вы можете указать, например, корневой раздел / или путь до любой другой директории.
  • -mount означает, что в процессе поиска не нужно переходить на другие файловые системы.
  • -type f означает, что мы ищем файлы.
  • -size +1G означает, что нужно найти файлы, размер которых превышает 1Gb. Размер можно указать в различных форматах:
    • b — блоки размером 512 байт. Числом указывается количество блоков.
    • c — в байтах. Например: -size +128с
    • w — в двухбайтовых словах
    • k — в килобайтах
    • M — в мегабайтах
    • G — в гигабайтах

    Команда find

    В результате выполнения команды будет выведен список файлов без какой-либо дополнительной информации.

    Вывод подробной информации

    Добавим в вывод информацию о каждом файле и отсортируем список по размеру. Выполняем команду

    find . -mount -type f -size +512M -print 2>/dev/null | xargs -r -d '\n' ls -lh | sort -k5,5 -h -r

    команда find xargs

    Данная команда состоит из трех частей:

    • Команда find ищет файлы, которые имеют размер больше 512 мегабайт.
    • Результирующий список файлов передается команде xargs , которая, в свою очередь, запускает команду ls -lh над этим списком файлов. В результате получается таблица с файлами и информацией о файлах. Опция -r , команды xarg, используется для того, чтобы не запускать команду ls, если команда find вернула пустой результат (не нашла файлов). Вместо -r можно использовать длинную запись — опцию —no-run-if-empty
      Опция -d ’\n’ используется, чтобы разделять список файлов только по символу новой строки (по \n ). А у нас так и есть — каждый файл на новой строке. Иначе неправильно будут обработаны файлы, в названии которых содержится пробел, так как по умолчанию команда xarg в качестве разделителя использует одновременно пробел, табуляцию или символ новой строки. Примечание: Для BSD-систем вместо -d ’\n’ нужно использовать опцию −0 , а у команды find вместо -print использовать -print0 . Пример: find . -mount -type f -size +512M -print0 2>/dev/null | xargs -0 ls -lh | sort -k5,5 -h -r
    • Затем результат команды ls передается команде sort , которая выполняет сортировку списка (таблицы) по пятой колонке — 5-я колонка содержит размеры файлов.
      Ключ -h означает, что результат нужно вывести в удобно-читаемом виде (human-readable).
      Ключ -r означает, что сортировку нужно выполнять по убыванию (reverse).

    Поиск больших файлов и директорий командой du

    Команда du используется для вывода размеров файлов и директорий в Linux. Ее можно использовать для поиска больших файлов и директорий. Для этого выполняется команда du и результат сортируется по размеру. Таким образом можно увидеть, кто занимает больше всего места на диске.

    Найдем пять самых больших файлов и директорий:

    команда du размеры файлов и директорий

    • Символ . указывает путь и означает текущую директорию. Для поиска в другой директории укажите вместо точки ее путь.
    • Опции -ahx означают:
      a — искать и файлы и директории;
      h — выводить информацию в удобно-читаемом формате;
      x — не выполнять поиск на других файловых системах.
    • sort -rh выполняет сортировку результата.
    • head −5 выводит только пять первых результатов.

    Источник

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