- Поиск в Linux с помощью команды find
- Общий синтаксис
- Описание опций
- Примеры использования find
- Поиск файла по имени
- Поиск по дате
- По типу
- Поиск по правам доступа
- Поиск файла по содержимому
- С сортировкой по дате модификации
- Лимит на количество выводимых результатов
- Поиск с действием (exec)
- Чистка по расписанию
- 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
Поиск в Linux с помощью команды find
Утилита find представляет универсальный и функциональный способ для поиска в Linux. Данная статья является шпаргалкой с описанием и примерами ее использования.
Общий синтаксис
— путь к корневому каталогу, откуда начинать поиск. Например, find /home/user — искать в соответствующем каталоге. Для текущего каталога нужно использовать точку «.».
— набор правил, по которым выполнять поиск.
* по умолчанию, поиск рекурсивный. Для поиска в конкретном каталоге можно использовать опцию maxdepth.
Описание опций
Опция | Описание |
---|---|
-name | Поиск по имени. |
-iname | Регистронезависимый поиск по имени. |
-type | |
-size | Размер объекта. Задается в блоках по 512 байт или просто в байтах (с символом «c»). |
-mtime | Время изменения файла. Указывается в днях. |
-mmin | Время изменения в минутах. |
-atime | Время последнего обращения к объекту в днях. |
-amin | Время последнего обращения в минутах. |
-ctime | Последнее изменение владельца или прав на объект в днях. |
-cmin | Последнее изменение владельца или прав в минутах. |
-user | Поиск по владельцу. |
-group | По группе. |
-perm | С определенными правами доступа. |
-depth | Поиск должен начаться не с корня, а с самого глубоко вложенного каталога. |
-maxdepth | Максимальная глубина поиска по каталогам. -maxdepth 0 — поиск только в текущем каталоге. По умолчанию, поиск рекурсивный. |
-prune | Исключение перечисленных каталогов. |
-mount | Не переходить в другие файловые системы. |
-regex | По имени с регулярным выражением. |
-regextype | Тип регулярного выражения. |
-L или -follow | Показывает содержимое символьных ссылок (симлинк). |
-empty | Искать пустые каталоги. |
-delete | Удалить найденное. |
-ls | Вывод как ls -dgils |
Показать найденное. | |
-print0 | Путь к найденным объектам. |
-exec <> \; | Выполнить команду над найденным. |
-ok | Выдать запрос перед выполнением -exec. |
Также доступны логические операторы:
Оператор | Описание |
---|---|
-a | Логическое И. Объединяем несколько критериев поиска. |
-o | Логическое ИЛИ. Позволяем команде find выполнить поиск на основе одного из критериев поиска. |
-not или ! | Логическое НЕ. Инвертирует критерий поиска. |
Полный набор актуальных опций можно получить командой man find.
Примеры использования find
Поиск файла по имени
1. Простой поиск по имени:
find / -name «file.txt»
* в данном примере будет выполнен поиск файла с именем file.txt по всей файловой системе, начинающейся с корня /.
2. Поиск файла по части имени:
* данной командой будет выполнен поиск всех папок или файлов в корневой директории /, заканчивающихся на .tmp
3. Несколько условий.
а) Логическое И. Например, файлы, которые начинаются на sess_ и заканчиваются на cd:
find . -name «sess_*» -a -name «*cd»
б) Логическое ИЛИ. Например, файлы, которые начинаются на sess_ или заканчиваются на cd:
find . -name «sess_*» -o -name «*cd»
в) Более компактный вид имеют регулярные выражения, например:
find . -regex ‘.*/\(sess_.*cd\)’
* где в первом поиске применяется выражение, аналогичное примеру а), а во втором — б).
4. Найти все файлы, кроме .log:
find . ! -name «*.log»
* в данном примере мы воспользовались логическим оператором !.
Поиск по дате
1. Поиск файлов, которые менялись определенное количество дней назад:
find . -type f -mtime +60
* данная команда найдет файлы, которые менялись более 60 дней назад.
2. Поиск файлов с помощью newer. Данная опция доступна с версии 4.3.3 (посмотреть можно командой find —version).
а) дате изменения:
find . -type f -newermt «2019-11-02 00:00»
* покажет все файлы, которые менялись, начиная с 02.11.2019 00:00.
find . -type f -newermt 2019-10-31 ! -newermt 2019-11-02
* найдет все файлы, которые менялись в промежутке между 31.10.2019 и 01.11.2019 (включительно).
б) дате обращения:
find . -type f -newerat 2019-10-08
* все файлы, к которым обращались с 08.10.2019.
find . -type f -newerat 2019-10-01 ! -newerat 2019-11-01
* все файлы, к которым обращались в октябре.
в) дате создания:
find . -type f -newerct 2019-09-07
* все файлы, созданные с 07 сентября 2019 года.
find . -type f -newerct 2019-09-07 ! -newerct «2019-09-09 07:50:00»
* файлы, созданные с 07.09.2019 00:00:00 по 09.09.2019 07:50
По типу
Искать в текущей директории и всех ее подпапках только файлы:
* f — искать только файлы.
Поиск по правам доступа
1. Ищем все справами на чтение и запись:
find / -perm 0666
2. Находим файлы, доступ к которым имеет только владелец:
find / -perm 0600
Поиск файла по содержимому
find / -type f -exec grep -i -H «content» <> \;
* в данном примере выполнен рекурсивный поиск всех файлов в директории / и выведен список тех, в которых содержится строка content.
С сортировкой по дате модификации
find /data -type f -printf ‘%TY-%Tm-%Td %TT %p\n’ | sort -r
* команда найдет все файлы в каталоге /data, добавит к имени дату модификации и отсортирует данные по имени. В итоге получаем, что файлы будут идти в порядке их изменения.
Лимит на количество выводимых результатов
Самый распространенный пример — вывести один файл, который последний раз был модифицирован. Берем пример с сортировкой и добавляем следующее:
find /data -type f -printf ‘%TY-%Tm-%Td %TT %p\n’ | sort -r | head -n 1
Поиск с действием (exec)
1. Найти только файлы, которые начинаются на sess_ и удалить их:
find . -name «sess_*» -type f -print -exec rm <> \;
* -print использовать не обязательно, но он покажет все, что будет удаляться, поэтому данную опцию удобно использовать, когда команда выполняется вручную.
2. Переименовать найденные файлы:
find . -name «sess_*» -type f -exec mv <> new_name \;
find . -name «sess_*» -type f | xargs -I ‘<>‘ mv <> new_name
3. Вывести на экран количество найденных файлов и папок, которые заканчиваются на .tmp:
find . -name «*.tmp» | wc -l
4. Изменить права:
find /home/user/* -type d -exec chmod 2700 <> \;
* в данном примере мы ищем все каталоги (type d) в директории /home/user и ставим для них права 2700.
5. Передать найденные файлы конвееру (pipe):
find /etc -name ‘*.conf’ -follow -type f -exec cat <> \; | grep ‘test’
* в данном примере мы использовали find для поиска строки test в файлах, которые находятся в каталоге /etc, и название которых заканчивается на .conf. Для этого мы передали список найденных файлов команде grep, которая уже и выполнила поиск по содержимому данных файлов.
6. Произвести замену в файлах с помощью команды sed:
find /opt/project -type f -exec sed -i -e «s/test/production/g» <> \;
* находим все файлы в каталоге /opt/project и меняем их содержимое с test на production.
Чистка по расписанию
Команду find удобно использовать для автоматического удаления устаревших файлов.
Открываем на редактирование задания cron:
0 0 * * * /bin/find /tmp -mtime +14 -exec rm <> \;
* в данном примере мы удаляем все файлы и папки из каталога /tmp, которые старше 14 дней. Задание запускается каждый день в 00:00.
* полный путь к исполняемому файлу find смотрим командой which find — в разных UNIX системах он может располагаться в разных местах.
Источник
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.
Источник