Linux быстрый поиск файлов

Поиск в Linux с помощью команды find

Обновлено

Обновлено: 01.02.2022 Опубликовано: 25.07.2016

Утилита find представляет универсальный и функциональный способ для поиска в Linux. Данная статья является шпаргалкой с описанием и примерами ее использования.

Общий синтаксис

путь к корневому каталогу, откуда начинать поиск. Например, find /home/user — искать в соответствующем каталоге. Для текущего каталога нужно использовать точку «.». набор правил, по которым выполнять поиск. * по умолчанию, поиск рекурсивный. Для поиска в конкретном каталоге можно использовать опцию maxdepth.

Описание опций

Также доступны логические операторы:

Оператор Описание
-a Логическое И. Объединяем несколько критериев поиска.
-o Логическое ИЛИ. Позволяем команде find выполнить поиск на основе одного из критериев поиска.
-not или ! Логическое НЕ. Инвертирует критерий поиска.

Полный набор актуальных опций можно получить командой man find.

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

Поиск файла по имени

* в данном примере будет выполнен поиск файла с именем file.txt по всей файловой системе, начинающейся с корня /.

2. Поиск файла по части имени:

* данной командой будет выполнен поиск всех папок или файлов в корневой директории /, заканчивающихся на .tmp

а) Логическое И. Например, файлы, которые начинаются на sess_ и заканчиваются на cd:

find . -name «sess_*» -a -name «*cd»

б) Логическое ИЛИ. Например, файлы, которые начинаются на sess_ или заканчиваются на cd:

find . -name «sess_*» -o -name «*cd»

в) Более компактный вид имеют регулярные выражения, например:

* где в первом поиске применяется выражение, аналогичное примеру а), а во втором — б).

4. Найти все файлы, кроме .log:

* в данном примере мы воспользовались логическим оператором !.

Поиск по дате

1. Поиск файлов, которые менялись определенное количество дней назад:

* данная команда найдет файлы, которые менялись более 60 дней назад.

find . -mmin -20 -mmin +10 -type f

* найти все файлы, которые менялись более 10 минут, но не более 20-и.

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

По типу

Искать в текущей директории и всех ее подпапках только файлы:

Читайте также:  Astra linux запуск exe файлов

* f — искать только файлы.

Поиск по правам доступа

1. Ищем все справами на чтение и запись:

2. Находим файлы, доступ к которым имеет только владелец:

Поиск файла по содержимому

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. Переместить найденные файлы:

find . -name «sess_*» -type f -exec mv <> /new/path/ \;

* в данном примере мы переместим все найденные файлы в каталог /new/path/.

4. Вывести на экран количество найденных файлов и папок, которые заканчиваются на .tmp:

find /home/user/* -type d -exec chmod 2700 <> \;

* в данном примере мы ищем все каталоги (type d) в директории /home/user и ставим для них права 2700.

6. Передать найденные файлы конвееру (pipe):

find /etc -name ‘*.conf’ -follow -type f -exec cat <> \; | grep ‘test’

* в данном примере мы использовали find для поиска строки test в файлах, которые находятся в каталоге /etc, и название которых заканчивается на .conf. Для этого мы передали список найденных файлов команде grep, которая уже и выполнила поиск по содержимому данных файлов.

7. Произвести замену в файлах с помощью команды 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 системах он может располагаться в разных местах.

Источник

10 ways to use the Linux find command

Discover what you’re looking for, find misplaced data, and troubleshoot everyday problems with this handy Linux command.

Magnifying glass with blue background

The find command is one of the most useful Linux commands, especially when you’re faced with the hundreds and thousands of files and folders on a modern computer. As its name implies, find helps you find things, and not just by filename.

Читайте также:  Запуск node js linux

Whether you’re on your own computer or trying to support someone on an unfamiliar system, here are 10 ways find can help you locate important data.

[ Keep your most commonly used commands handy with the Linux commands cheat sheet. ]

1. Find a single file by name

When you know the name of a file but can’t remember where you saved it, use find to search your home directory. Use 2>/dev/null to silence permission errors (or use sudo to gain all permissions).

$ find / -name "Foo.txt" 2>/dev/null /home/seth/Documents/Foo.txt

2. Find a single file by approximate name

If you can’t remember the exact name of the file, or you’re not sure whether you capitalized any characters, you can do a partial and case-insensitive search like this:

$ find / -iname "*foo*txt" 2>/dev/null /home/seth/Documents/Foo.txt /home/seth/Documents/foo.txt /home/seth/Documents/foobar.txt

3. Find everything

The ls -R command lists the contents of a directory recursively, meaning that it doesn’t just list the target you provide for it, but also descends into every subdirectory within that target (and every subdirectory in each subdirectory, and so on.) The find command has that function too, by way of the -ls option:

$ find ~/Documents -ls 3554235 0 drwxr-xr-x [. ] 05:36 /home/seth/Documents/ 3554224 0 -rw-rw-r-- [. ] 05:36 /home/seth/Documents/Foo 3766411 0 -rw-rw-r-- [. ] 05:36 /home/seth/Documents/Foo/foo.txt 3766416 0 -rw-rw-r-- [. ] 05:36 /home/seth/Documents/Foo/foobar.txt

IT Automation ebook

Notice that I don’t use 2>/dev/null in this instance because I’m only listing the contents of a file path within my home directory, so I don’t anticipate permission errors.

4. Find by content

A find command doesn’t have to perform just one task. In fact, one of the options in find enables you to execute a different command on whatever results find returns. This can be especially useful when you need to search for a file by content rather than by name, or you need to search by both.

$ find ~/Documents/ -name "*txt" -exec grep -Hi penguin <> \; /home/seth/Documents/Foo.txt:I like penguins. /home/seth/Documents/foo.txt:Penguins are fun.

5. Find files by type

You can display files, directories, symlinks, named pipes, sockets, and more using the -type option.

$ find ~ -type f /home/seth/.bash_logout /home/seth/.bash_profile /home/seth/.bashrc /home/seth/.emacs /home/seth/.local/share/keyrings/login.keyring /home/seth/.local/share/keyrings/user.keystore /home/seth/.local/share/gnome-shell/gnome-overrides-migrated [. ]

As long as you’re using the GNU version of find , you can include multiple file types in your search results:

$ find ~ -type f,l -name "notebook*" /home/seth/notebook.org /home/seth/Documents/notebook-alias.org

6. List just directories

A shortcoming of the ls command is that you can’t filter its results by file type, so it can be noisy if you only want a listing of directories in a path. The find command combined with the -type d option is a better choice:

$ find ~/Public -type d find ~/Public/ -type d /home/seth/Public/ /home/seth/Public/example.com /home/seth/Public/example.com/www /home/seth/Public/example.com/www/img /home/seth/Public/example.com/www/font /home/seth/Public/example.com/www/style

7. Limit listing results

With hundreds of files in a default user directory and thousands more outside of that, sometimes you get more results from find than you want. You can limit the depth of searches with the -maxdepth option, followed by the number of directories you want find to descend into after the starting point:

$ find ~/Public/ -maxdepth 1 -type d /home/seth/Public/ /home/seth/Public/example.com

8. Find empty files

Sometimes it’s helpful to discover empty files as a way to declutter:

$ find ~ -type f -empty random.idea.txt

Great Linux resources

Technically, you can use find to remove empty files, but programmatic removal of files is dangerous. For instance, if you forget to include -type f in a search for empty files, you get directories in your results. By adding a delete flag, you would remove potentially important directory structures.

Читайте также:  Узнать серийный номер сервера linux

It’s vital to compose your find command and then verify the results before deleting. Furthermore, a misplaced delete flag in find can delete results before qualifying them (in other words, you can delete directories in a command intended to delete only files by placing the delete flag before the type flag).

I prefer to use xargs or Parallel and a trash command on the rare occasion that I remove files with find .

9. Find files by age

The -mtime option allows you to limit a search to files older than, but also files newer than, some value times 24.

$ find /var/log -iname "*~" -o -iname "*log*" -mtime +30

The + before the -mtime number doesn’t mean to add that number to the time. It’s a conditional statement that matches (in this example) a value greater than 24 times 30. In other words, the sample code finds log files that haven’t been modified in a month or more.

To find log files modified within the past week, you can use the — conditional:

$ find /var/log -iname "*~" -o -iname "*log*" -mtime -7 /var/log/tallylog /var/log/cups/error_log /var/log/cups/access_log /var/log/cups/page_log /var/log/anaconda/anaconda.log /var/log/anaconda/syslog /var/log/anaconda/X.log [. ]

You already know about the -ls flag, so you can combine that with these commands for clarity:

$ find /var/log -iname "*~" -o -iname "*log*" -mtime -7 -ls -rw------- 1 root root 0 Jun 9 18:20 /var/log/tallylog -rw------- 1 root lp 332 Aug 11 15:05 /var/log/cups/error_log -rw------- 1 root lp 332 Aug 11 15:05 /var/log/cups/access_log -rw------- 1 root lp 332 Aug 11 15:05 /var/log/cups/page_log -rw------- 1 root root 53733 Jun 9 18:24 /var/log/anaconda/anaconda.log -rw------- 1 root root 835513 Jun 9 18:24 /var/log/anaconda/syslog -rw------- 1 root root 21131 Jun 9 18:24 /var/log/anaconda/X.log [. ]

10. Search a path

Sometimes you know the directory structure leading up to a file you need; you just don’t know where the directory structure is located within the system. To search within a path string, you can use the -ipath option, which treats dots and slashes not as regex characters but as dots and slashes.

$ find / -type d -name 'img' -ipath "*public_html/example.com*" 2>/dev/null /home/tux/Public/public_html/example.com/font

Found it

The find command is an essential tool for a sysadmin. It’s useful when investigating or getting to know a new system, finding misplaced data, and troubleshooting everyday problems. But it’s also just a convenience tool.

[ Download the Linux find cheat sheet to keep all these shortcuts in one place. ]

You don’t need a «good» reason to use find . Using find makes it easier to search for something instead of traversing your system. It’s an understated but infinitely useful tool that embodies the sublime pleasure of everyday Linux. Start using it today, and find out what makes it great.

Источник

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