Как найти файл по размеру линукс

Время на прочтение
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

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

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

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

Утилита find предустановлена по умолчанию во всех Linux дистрибутивах, поэтому вам не нужно будет устанавливать никаких дополнительных пакетов. Это очень важная находка для тех, кто хочет использовать командную строку наиболее эффективно.

Команда find имеет такой синтаксис:

find [папка] [параметры] критерий шаблон [действие]

Папка — каталог в котором будем искать

Параметры — дополнительные параметры, например, глубина поиска, и т д

Критерий — по какому критерию будем искать: имя, дата создания, права, владелец и т д.

Шаблон — непосредственно значение по которому будем отбирать файлы.

Основные параметры команды find

Я не буду перечислять здесь все параметры, рассмотрим только самые полезные.

  • -P — никогда не открывать символические ссылки.
  • -L — получает информацию о файлах по символическим ссылкам. Важно для дальнейшей обработки, чтобы обрабатывалась не ссылка, а сам файл.
  • -maxdepth — максимальная глубина поиска по подкаталогам, для поиска только в текущем каталоге установите 1.
  • -depth — искать сначала в текущем каталоге, а потом в подкаталогах.
  • -mount искать файлы только в этой файловой системе.
  • -version — показать версию утилиты find.
  • -print — выводить полные имена файлов.
  • -type f — искать только файлы.
  • -type d — поиск папки в Linux.

Критерии

Критериев у команды find в Linux очень много, и мы опять же рассмотрим только основные.

  • -name — поиск файлов по имени.
  • -perm — поиск файлов в Linux по режиму доступа.
  • -user — поиск файлов по владельцу.
  • -group — поиск по группе.
  • -mtime — поиск по времени модификации файла.
  • -atime — поиск файлов по дате последнего чтения.
  • -nogroup — поиск файлов, не принадлежащих ни одной группе.
  • -nouser — поиск файлов без владельцев.
  • -newer — найти файлы новее чем указанный.
  • -size — поиск файлов в Linux по их размеру.

Примеры использования

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

1. Поиск всех файлов

Показать все файлы в текущей директории:

find

find .

find . -print

Все три команды покажут одинаковый результат. Точка здесь означает текущую папку. Вместо неё можно указать любую другую.

2. Поиск файлов в определенной папке

Показать все файлы в указанной директории:

find ./Изображения

Искать файлы по имени в текущей папке:

find . -name "*.png

Поиск по имени в текущей папке:

find . -name "testfile*"

Не учитывать регистр при поиске по имени:

find . -iname "TeStFile*"

3. Ограничение глубины поиска

Поиска файлов по имени в Linux только в этой папке:

find . -maxdepth 1 -name "*.php"

4. Инвертирование шаблона

Найти файлы, которые не соответствуют шаблону:

find . -not -name "test*"

5. Несколько критериев

Поиск командой find в Linux по нескольким критериям, с оператором исключения:

find . -name "test" -not -name "*.php"

Найдет все файлы, начинающиеся на test, но без расширения php. А теперь рассмотрим оператор ИЛИ:

find -name "*.html" -o -name "*.php"

Эта команда найдёт как php, так и html файлы.

6. Тип файла

По умолчанию find ищет как каталоги, так и файлы. Если вам необходимо найти только каталоги используйте критерий type с параметром d. Например:

find . -type d -name "Загрузки"

Для поиска только файлов необходимо использовать параметр f:

find . -type f -name "Загрузки"

6. Несколько каталогов

Искать в двух каталогах одновременно:

find ./test ./test2 -type f -name "*.c"

7. Поиск скрытых файлов

Найти скрытые файлы только в текущей папке. Имена скрытых файлов в Linux начинаются с точки:

find . -maxdepth 1 -type f -name ".*"

8. Поиск по разрешениям

Найти файлы с определенной маской прав, например, 0664:

find . -type f -perm 0664

Права также можно задавать буквами для u (user) g (group) и o (other). Например, для того чтобы найти все файлы с установленным флагом Suid в каталоге /usr выполните:

sudo find /usr -type f -perm /u=s

Поиск файлов доступных владельцу только для чтения только в каталоге /etc:

find /etc -maxdepth 1 -perm /u=r

Найти только исполняемые файлы:

find /bin -maxdepth 2 -perm /a=x

9. Поиск файлов в группах и пользователях

Найти все файлы, принадлежащие пользователю:

find . -user sergiy

Поиск файлов в Linux принадлежащих группе:

find /var/www -group www-data

10. Поиск по дате модификации

Поиск файлов по дате в Linux осуществляется с помощью параметра mtime. Найти все файлы модифицированные 50 дней назад:

find / -mtime 50

Поиск файлов в Linux открытых N дней назад:

find / -atime 50

Найти все файлы, модифицированные между 50 и 100 дней назад:

find / -mtime +50 -mtime -100

Найти файлы измененные в течении часа:

find . -cmin 60

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

Найти все файлы размером 50 мегабайт:

find / -size 50M

От пятидесяти до ста мегабайт:

find / -size +50M -size -100M

Найти самые маленькие файлы:

find . -type f -exec ls -s {} ; | sort -n -r | head -5

Самые большие:

find . -type f -exec ls -s {} ; | sort -n | head -5

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

find /tmp -type f -empty

find ~/ -type d -empty

13. Действия с найденными файлами

Для выполнения произвольных команд для найденных файлов используется опция -exec. Например, для того чтобы найти все пустые папки и файлы, а затем выполнить ls для получения подробной информации о каждом файле используйте:

find . -empty -exec ls -ld {} ;

Удалить все текстовые файлы в tmp

find /tmp -type f -name "*.txt" -exec rm -f {} ;

Удалить все файлы больше 100 мегабайт:

find /home/bob/dir -type f -name *.log -size +100M -exec rm -f {} ;

Выводы

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

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

Contents

  1. Introduction
  2. The Basics

    1. Locating Files by Name
    2. Locating Files by Size
    3. Locating Files by Access Time
  3. Advanced Usage

    1. Combining Searches
    2. Acting On The files
    3. Using xargs
  4. More Information

Introduction

The GNU find command searches files within a directory and its subdirectories according to several criteria such as name, size and time of last read/write. By default find prints the name of the located files but it can also perform commands on these files.

The GNU find command is part of the GNU findutils and is installed on every Ubuntu system. findutils is actually made up of 4 utilities:

  1. find — search for files in a directory hierarchy, whether its a database or not

  2. locate — list files in databases that match a pattern, i.e. find inside updatedb’s list

  3. updatedb — update a file name database, i.e. collection of db’s only, such as sqlite

  4. xargs — build and execute command lines from standard input — usually you do this directly w/o xargs

This wiki page will be only be dealing with find while also briefly mentioning xargs. Hopefully locate and updatedb will be covered on their own page in the near future. «find», like «locate», can find database-files as well, but «locate» is more specialized for this task. You would run updatedb before using locate, which relies on the data produced by «updateDB».

The Basics

find ~ -name readme.txt 

will find this file below the home directory. find works incredibly fast on the second run! You can search the whole / root-dir-tree in a mere approx. 3 seconds (on second run, when cache is effective) on a 500 GB ext4-fs hard disk.

The syntax for using find is:

find [-H] [-L] [-P] [path...] [expression]

The 3 options [-H] [-L] [-P] are not commonly seen but should at least be noted if only to realise that the -P option will be the default unless another option is specified:

  • -H : Do not follow symbolic links, except while processing the command line arguments.
  • -L : Follow symbolic links.
  • -P : Never follow symbolic links: the default option.

The option [path…] refers to the particular location that you wish to search, whether it be your $HOME directory, a particular directory such as /usr, your present working directory which can simply be expressed as ‘.’ or your entire computer which can be expressed as ‘/’.

The option [expression] refers to one or a series of options which effect the overall option of the find command. These options can involve a search by name, by size, by access time or can also involve actions taken upon these files.

Locating Files by Name

The most common use of find is in the search for a specific file by use of its name. The following command searches the home directory and all of its subdirectories looking for the file mysong.ogg:

find $HOME -name 'mysong.ogg' 

It is important to get into the habit of quoting patterns in your search as seen above or your search results can be a little unpredictable. Such a search can be much more sophisticated though. For example if you wished to search for all of the ogg files in your home directory, some of which you think might be named ‘OGG’ rather than ‘ogg’, you would run:

find $HOME -iname '*.ogg' 

Here the option ‘-iname’ performs a case-insensitive search while the wildcard character ‘*’ matches any character, or number of characters, or zero characters. To perform the same search on your entire drive you would run:

sudo find / -iname '*.ogg' 

This could be a slow search depending on the number of directories, sub-directories and files on your system. This highlights an important difference in the way that find operates in that it examines the system directly each time unlike programs like locate or slocate which actually examine a regularly updated database of filnames and locations.

Locating Files by Size

Another possible search is to search for files by size. To demonstrate this we can again search the home directory for Ogg Vorbis files but this time looking for those that are 100 megabytes or larger:

find $HOME -iname '*.ogg' -size +100M 

There are several options with -size, I have used ‘M’ for ‘megabytes’ here but ‘k’ for ‘kilobytes’ can be used or ‘G’ for ‘Gigabytes’. This search can then be altered to look for files only that are less than 100 megabytes:

find $HOME -iname '*.ogg' -type f -size -100M 

Are you starting to see the power of find, and the thought involved in constructing a focused search? If you are interested there is more discussion of these combined searches in the Advanced Usage section below.

Locating Files by Access Time

It is also possible to locate files based on their access time or the time that they were last used, or viewed by the system. For example to show all files that have not been accessed in the $HOME directory for 30 days or more:

find $HOME -atime +30

This type of search is normally more useful when combined with other find searches. For example one could search for all ogg files in the $HOME directory that have an access time of greater than 30 days:

find $HOME -iname '*.ogg' -atime +30

The syntax works from left to right and by default find joins the 2 expressions with an implied «and». This is dealt with in more depth in the section below entitled «Combining Searches».

Advanced Usage

The sections above detail the most common usage of find and this would be enough for most searches. However there are many more possibilities in the usage of find for quite advanced searches and this sections discusses a few of these possibilities.

Combining Searches

It is possible to combine searches when using find with the use of what is known in the find man pages as operators. These are

as in

find ~ -name 'xx*' -and -not -name 'xxx'

unless you prefer the cryptic syntax below (-o instead of -or)

The classic example is the use of a logical AND syntax:

find $HOME -iname '*.ogg' -size +20M 

This find search performs initially a case insensitive search for all the ogg files in your $HOME directory and for every true results it then searches for those with a size of 20 megabytes and over. This contains and implied operator which could be written joined with an -a. This search can be altered slightly by use of an exclamation point to signify negation of the result:

find $HOME -iname '*.ogg' ! -size +20M 

This performs the same search as before but will look for ogg files that are not greater than 20 megabytes. It is possible also to use a logical OR in your find search:

find $HOME -iname '*.ogg' -o -iname '*.mp3'

This will perform a case insensitive search in the $HOME directories and find all files that are either ogg OR mp3 files. There is great scope here for creating very complex and finely honed searches and I would encourage a through reading of the find man pages searching for the topic OPERATORS.

Acting On The files

One advanced but highly useful aspect of find usage is the ability to perform a user-specified action on the result of a find search. For example the following search looks for all ogg vorbis files in the $HOME directory and then uses -exec to pass the result to the du program to give the size of each file:

find $HOME -name '*.ogg' -type f -exec du -h '{}' ;

This syntax is often used to delete files by using -exec rm -rf but this must be used with great caution, if at all, as recovery of any deleted files can be quite difficult.

Using xargs

xargs <<< / ls

same as: ls /

xargs feeds here-string / as parameter («argument») to the ls command

When using a really complex search it is often a good idea to use another member of the findutils package: xargs. Without its use the message Argument list too long could be seen signalling that the kernel limit on the combined length of a commandline and its environment variables has been exceeded. xargs works by feeding the results of the search to the subsequent command in batches calculated on the system capabilities (based on ARG_MAX). An example:

find /tmp -iname '*.mp3' -print0 | xargs -0 rm

This example searches the /tmp folder for all mp3 files and then deletes them. You will note the use of both -print0 and xargs -0 which is a deliberate strategy to avoid problems with spaces and/or newlines in the filenames. Modern kernels do not have the ARG_MAX limitation but to keep your searches portable it is an excellent idea to use xargs in complex searches with subsequent commands.

More Information

  • Linux Basics: A gentle introduction to ‘find’ — An Ubuntu Forums guide that was incorporated into this wiki article with the gracious permission of its author.

  • Using Find — Greg’s Wiki — A very comprehensive guide to using find, along similar lines to this guide, that is well worth reading through.

  • Linux Tutorial: The Power of the Linux Find Command The amazing Nixie Pixel gives a video demonstration of find.


CategoryCommandLine

Explanation: Use unix command find Using -size oprator

The find utility recursively descends the directory tree for each path listed, evaluating an expression (composed of the ‘primaries’ and ‘operands’) in terms of each file in the tree.

Solution: According to the documentation

-size n[ckMGTP]
             True if the file's size, rounded up, in 512-byte blocks is n.  If n is fol-
             lowed by a c, than the primary is true if the file's size is n bytes (charac-
             ters).  Similarly if n is followed by a scale indicator than the file's size
             is compared to n scaled as:

             k       kilobytes (1024 bytes)
             M       megabytes (1024 kilobytes)
             G       gigabytes (1024 megabytes)
             T       terabytes (1024 gigabytes)
             P       petabytes (1024 terabytes)

Usage: perform find operation with -size flag and threshold measurement arguments: more than(+)/less than(-), number(n) and measurement type (k/M/G/T/P).

Formula: find <path> -size [+/-]<Number><Measurement>

Examples:

1.Greater Than — Find all files in my current directory (.) that greater than 500 kilobyte

find . -size +500k 

2.Less Than — Find all files in my current directory (.) that less than 100 megabyte.

find . -size -100M

3.Range — Find specific file (test) in my current directory (.) that greater than 500 kilobyte less than 100 megabyte (500k-1000k)

find . -name "test" -size +500k -size -100M

4.Complex Range with Regex Find all .mkv files in all filesystem (root /) that are greater than 1 gigabyte and created this month, and present info of them.

find / -name "*.mkv" -size +1G -type f -ctime -4w | xargs ls -la

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

  • Syntax of find command to find files bigger than given size in Linux.
  • Find files larger than 4gb in Linux.
  • Find files larger than 1gb in Linux.
  • Find files larger than 500 MB in Linux.
  • Find files larger than 100 MB in Linux.
  • Find files larger than 100 MB in Linux.
  • Find files larger than 0 Bytes in Linux.

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.

Advertisements

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

find <directory> -type f -size +N<Unit Type>

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:

  • Linux: Create directory or folder using mkdir command
  • Find Files containing specific Text in Linux
  • Recursively Count Files in a directory in Linux
  • Linux – Replace String in Files
  • G-> for gibibytes
  • M-> for megabytes
  • K-> for kibibytes
  • b-> for bytes

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,

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

find /usr -type f -size +4G

Output:

/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 }'

Output:

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

find /usr -type f -size +1G

Output:

/usr/logs/error_logs.txt<br>/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.

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 }'

Output:

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

Output:

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

Output:

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

find /usr -type f -size +50M

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.

find /usr -type f -size +0b

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.

Понравилась статья? Поделить с друзьями:
  • Как найти крышу для защиты
  • Как найти обстоятельства выраженные наречием
  • Ограбление произошло в полном соответствии с указанной статьей уголовного кодекса как исправить
  • Как найти людей в рабстве
  • Как найти массовую долю оксида водорода