Linux find files with file size

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

Источник

How To Find Files Bigger Or Smaller Than X Size In Linux

Let us say you want to find files which are less than or greater than a certain size in your system. How would you do that? Manually check each and every file’s size? No, it is time consuming task. Besides, a good system admin won’t do it. There is always an easiest and fastest way to do things in Linux. This brief tutorial covers how to find files bigger or smaller than X size in Linux and Unix operating systems.

Find files bigger or smaller than X size

Using find command, we can also easily find files bigger or smaller than given size.

For instance, to find files that are bigger than 4GB in a directory, just enter:

Sample output from my system:

As you can see, I have some files with size bigger than 4GiB. Here, the dot (.) indicates the current directory.

To search for files bigger than 4 GiB in the entire filesystem, run:

To know files bigger than X size in a specific directory, replace the dot (.) in the above command with the directory path like below.

The above command find files bigger than 4GiB in Downloads directory.

Similarly, to find the files which are smaller than X size, for example 4GiB, use the following command:

You can use size switch for other formats, such as

  • ‘c’ for bytes
  • ‘w’ for two-byte words
  • ‘k’ for Kilobytes
  • ‘M’ for Megabytes
  • ‘G’ for Gigabytes

For example, to find files which are bigger than 4MB, use the following command:

To find files smaller than 4MB, use this command:

You might wonder how to find files between a certain size. For instance, you can find files between 30MB and 40MB using the following command:

To find files of exact size, for example 30MB, run:

For more details, refer man pages.

Update:

As one of the reader mentioned in the comment section below, the find command can also display a long listing of all the files it finds by using the -exec switch. The command below will find all of the files between 30M and 40M, and display a long listing of each file.

Do you know any other useful and easiest way to find files which are smaller or bigger than a particular size? Please feel free to comment them in comment section below.

Источник

Команда find в Linux

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

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

Основная информация о Find

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

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

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

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

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

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

find . -iname «test*»

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»

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

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

find ./test ./test2 -type f -name «*.c»

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

Найти скрытые файлы:

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

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

find . type f -perm 0664

Найти файлы с установленным флагом suid/guid:

find / -perm 2644

find / -maxdepth 2 -perm /u=s

Поиск файлов только для чтения:

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

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

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

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

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

find . -user sergiy

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

find /var/www -group developer

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

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

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

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

find / -mtime +50 –mtime -100

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

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

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

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

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

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

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

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

Источник

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,

  • 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,

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.

Output:

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,

Output:

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.

Output:

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

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:

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

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

Output:

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.

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,

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,

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.

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,

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

Источник

Читайте также:  Mac os mojave поддержка устройств
Оцените статью