- Команда find в Linux – мощный инструмент сисадмина
- Поиск по имени
- Поиск по типу файла
- Поиск по размеру файла
- Единицы измерения файлов:
- Поиск пустых файлов и каталогов
- Поиск времени изменения
- Поиск по времени доступа
- Поиск по имени пользователя
- Поиск по набору разрешений
- Операторы
- Действия
- -delete
- Заключение
- How to find files and directories in Linux
- Basic functionality of find
- Specifying where to search
- Finding by name
- Finding only files, or only directories
- Finding files based on size
- Finding files based on modification, access, or status change
- Redirecting output to a text file
- Suppressing error messages
- Examples
Команда find в Linux – мощный инструмент сисадмина
Иногда критически важно быстро найти нужный файл или информацию в системе. Порой можно ограничиться стандартами функциями поиска, которыми сейчас обладает любой файловый менеджер, но с возможностями терминала им не сравниться.
Команда find – это невероятно мощный инструмент, позволяющий искать файлы не только по названию, но и по:
- Дате добавления.
- Содержимому.
- Регулярным выражениям.
Данная команда будет очень полезна системным администраторам для:
- Управления дисковым пространством.
- Бэкапа.
- Различных операций с файлами.
Команда find в Linux производит поиск файлов и папок на основе заданных вами критериев и позволяет выполнять действия с результатами поиска.
Синтаксис команды find:
- directory-to-search (каталог поиска) – это отправной каталог, с которой find начинает поиск файлов по всем подкаталогам, которые находятся внутри. Если не указать путь, тогда поиск начнется в текущем каталоге;
- criteria (критерий) – критерий, по которым нужно искать файлы;
- action (действие) – что делать с каждым найденным файлом, соответствующим критериям.
Поиск по имени
Следующая команда ищет файл s.txt в текущем каталоге:
- . (точка) – файл относится к нынешнему каталогу
- -name – критерии по которым осуществляется поиск. В данном случае поиск по названию файла.
В данном случае критерий -name учитывает только символы нижнего регистра и файл S.txt не появиться в результатах поиска. Чтобы убрать чувствительность к регистру необходимо использовать –iname.
Для поиска всех изображений c расширением .png нужно использовать шаблон подстановки *.png:
Можно использовать название каталога для поиска. Например, чтобы с помощью команды find найти все png изображения в каталоге home:
Если выдает слишком много ошибок в отказе разрешения, тогда можно добавить в конец команды – 2> /dev/null. Таким образом сообщения об ошибках будут перенаправляться по пути dev/null, что обеспечит более чистую выдачу.
Поиск по типу файла
Критерий -type позволяет искать файлы по типу, которые бывают следующих видов:
- f – простые файлы;
- d – каталоги;
- l – символические ссылки;
- b – блочные устройства (dev);
- c – символьные устройства (dev);
- p – именованные каналы;
- s – сокеты;
Например, указав критерий -type d будут перечислены только каталоги:
Поиск по размеру файла
Допустим, что вам необходимо найти все большие файлы. Для таких ситуаций подойдет критерий -size.
- «+» — Поиск файлов больше заданного размера
- «-» — Поиск файлов меньше заданного размера
- Отсутствие знака означает, что размер файлов в поиске должен полностью совпадать.
В данном случае поиск выведет все файлы более 1 Гб (+1G).
Единицы измерения файлов:
Поиск пустых файлов и каталогов
Критерий -empty позволяет найти пустые файлы и каталоги.
Поиск времени изменения
Критерий -cmin позволяет искать файлы и каталоги по времени изменения. Для поиска всех файлов, измененных за последний час (менее 60 мин), нужно использовать -60:
Таким образом можно найти все файлы в текущем каталоге, которые были созданы или изменены в течение часа (менее 60 минут).
Для поиска файлов, которые наоборот были изменены в любое время кроме последнего часа необходимо использовать +60.
Поиск по времени доступа
Критерий -atime позволяет искать файлы по времени последнего доступа.
Таким образом можно найти файлы, к которым не обращались последние полгода (180 дней).
Поиск по имени пользователя
Опция –user username дает возможность поиска всех файлов и каталогов, принадлежащих конкретному пользователю:
Таким образом можно найти все файлы пользователя tisha в каталоге home, а 2>/dev/null сделает выдачу чистой без ошибок в отказе доступа.
Поиск по набору разрешений
Критерий -perm – ищет файлы по определенному набору разрешений.
Поиск файлов с разрешениями 777.
Операторы
Для объединения нескольких критериев в одну команду поиска можно применять операторы:
Например, чтобы найти файлы размером более 1 Гбайта пользователя tisha необходимо ввести следующую команду:
Если файлы могут принадлежать не только пользователю tisha, но и пользователю pokeristo, а также быть размером более 1 Гбайта.
Перед скобками нужно поставить обратный слеш «\».
Действия
К команде find можно добавить действия, которые будут произведены с результатами поиска.
- -delete — Удаляет соответствующие результатам поиска файлы
- -ls — Вывод более подробных результатов поиска с:
- Размерами файлов.
- Количеством inode.
- -print Стоит по умолчанию, если не указать другое действие. Показывает полный путь к найденным файлам.
- -exec Выполняет указанную команду в каждой строке результатов поиска.
-delete
Полезен, когда необходимо найти и удалить все пустые файлы, например:
Перед удалением лучше лишний раз себя подстраховать. Для этого можно запустить команду с действием по умолчанию -print.
Данное действие является особенным и позволяет выполнить команду по вашему усмотрению в результатах поиска.
- command – это команда, которую вы желаете выполнить для результатов поиска. Например:
- rm
- mv
- cp
- <> – является результатами поиска.
- \; — Команда заканчивается точкой с запятой после обратного слеша.
С помощью –exec можно написать альтернативу команде –delete и применить ее к результатам поиска:
Другой пример использования действия -exec:
Таким образом можно скопировать все .jpg изображения в каталог backups/fotos
Заключение
Команду find можно использовать для поиска:
- Файлов по имени.
- Дате последнего доступа.
- Дате последнего изменения.
- Имени пользователя (владельца файла).
- Имени группы.
- Размеру.
- Разрешению.
- Другим критериям.
С полученными результатами можно сразу выполнять различные действия, такие как:
- Удаление.
- Копирование.
- Перемещение в другой каталог.
Команда find может сильно облегчить жизнь системному администратору, а лучший способ овладеть ей – больше практиковаться.
Источник
How to find files and directories in Linux
In Linux operating systems, the find command may be used to search for files and directories on your computer. To proceed, select a link from the following list or go through each section in order.
To use find, begin by opening a terminal session to access the command line.
Basic functionality of find
Running find without any options produces a list of every file and directory in and beneath the working directory. For instance, if your working directory is /home/hope/Documents, running find outputs the following:
- Every file in /home/hope/Documents.
- Every subdirectory in /home/hope/Documents.
- Every file in each of those subdirectories.
Let’s see it in action. First, let’s check our working directory using the pwd command:
Now let’s run find without any options:
In this example, we see a total of ten files and four subdirectories in and beneath our Documents folder.
Notice that the output starts with a single dot, which represents the working directory. Running find with no options is the same as specifying that the search should begin in the working directory, like this:
The example above is the «proper» way to use find. If you try to use it on another Unix-like operating system, such as FreeBSD, specifying a directory is required. It’s good practice to use this form of the command.
Specifying where to search
To only list files and subdirectories that are contained in the directory /home/hope/Documents/images, specify the first argument of the command as:
Notice that the full path is also shown in the results.
If our working directory is /home/hope/Documents, we can use the following command, which finds the same files:
But this time, the output reflects the starting location of the search and looks like this:
By default, the search looks in every subdirectory of your starting location. If you want to restrict how many levels of subdirectory to search, you can use the -maxdepth option with a number.
For instance, specifying -maxdepth 1 searches only in the directory where the search begins. If any subdirectories are found, they are listed, but not searched.
Specifying -maxdepth 2 searches the directory and one subdirectory deep:
Specifying -maxdepth 3 searches one level deeper than that:
Finding by name
To restrict your search results to match only files and directories with a certain name, use the -name option and put the name in quotes:
You can also use wildcards as part of your file name. For instance, to find all files whose name ends in .jpg, you can use an asterisk to represent the rest of the file name. When you run the command, the shell globs the file name into anything that matches the pattern:
Notice that our command didn’t list the file whose extension (in this case, JPG) is in capital letters. That’s because unlike other operating systems, such as Microsoft Windows, Linux file names are case-sensitive.
To perform a case-insensitive search instead, use the -iname option:
Finding only files, or only directories
To list files only and omit directory names from your results, specify -type f:
To list directories only and omit file names, specify -type d:
Finding files based on size
To display only files of a certain size, you can use the -size option. To specify the size, use a plus or minus sign (for «more than» or «less than»), a number, and a quantitative suffix, such as k, M, or G.
For instance, to find files that are «bigger than 50 kilobytes», use -size +50k:
For files «bigger than 10 megabytes», use -size +10M:
For «bigger than 1 gigabyte», use -size +1G:
For files in a certain size range, use two -size options. For instance, to find files «bigger than 10 megabytes, but smaller than 1 gigabyte», specify -size +10M -size -1G:
Finding files based on modification, access, or status change
The -mtime option restricts search by how many days since the file’s contents were modified. To specify days in the past, use a negative number. For example, to find only those files which were modified in the past two days (48 hours ago), use -mtime -2:
The -mmin option does the same thing, but in terms of minutes, not days. For instance, this command shows only files modified in the past half hour:
A similar option is -ctime, which checks when a file’s status was last changed, measured in days. A status change is a change in the file’s metadata. For instance, changing the permissions of a file is status change.
The option -cmin searches for a status change, measured in minutes.
You can also search for when a file was last accessed — in other words, when its contents were most recently viewed. The -atime option is used to search for files based upon their most recent access time, measured in days.
The -amin option performs the same search restriction, but measured in minutes.
Redirecting output to a text file
If you are performing a very large search, you may want to save your search results in a file, so that you can view the results later. You can do this by redirecting your find output to a file:
You can then open your results in a text editor, or print them with the cat command.
Alternatively, you can pipe your output to the tee command, which prints the output to the screen and write it to a file:
Suppressing error messages
You may receive the error message «Permission denied» when performing a search. For instance, if you search the root directory as a normal user:
You receive that error message if find tries to access a file your user account doesn’t have permission to read. You can perform the search as the superuser (root), which has complete access to every file on the system. But it’s not recommended to do things as root, unless there are no other options.
If all you need to do is hide the «Permission denied» messages, you can add 2&>1 | grep -v «Permission denied» to the end of your command, like this:
The above example filters out the «Permission denied» messages from your search. How?
2>&1 is a special redirect that sends error messages to the standard output to pipe the combined lines of output to the grep command. grep -v then performs an inverse match on «Permission denied», displaying only lines which do not contain that string.
Redirecting and using grep to filter the error messages is a useful technique when «Permission denied» is cluttering your search results and you can’t perform the search as root.
Examples
Find all files in your home directory and below which end in the extension «.txt«. Display only files accessed in the past two hours.
Find all files in the working directory and below whose name has the extension «.zip» and whose size is greater than 10 megabytes. Display only files whose contents were modified in the last 72 hours.
Perform a case-insensitive search for files that contain the word «report» in their name. If the search finds a directory with «report» in its name, do not display it. Search only in the working directory, and one directory level beneath it.
Источник