Как найти файл команда linux

Время на прочтение
5 мин

Количество просмотров 123K

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

Команда 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.

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

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

Синтаксис
Примеры
    Поиск по имени
    По дате
    По типу файла
    По правам
    По содержимому
    С сортировкой по дате изменения
    Лимиты
    Действия над найденными объектами
Запуск по расписанию в CRON

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

find <где искать> <опции>

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

<опции> — набор правил, по которым выполнять поиск.

* по умолчанию, поиск рекурсивный. Для поиска в конкретном каталоге можно использовать опцию maxdepth.

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

Опция Описание
-name Поиск по имени.
-iname Регистронезависимый поиск по имени.
-type

Тип объекта поиска. Возможные варианты:

  • f — файл;
  • d — каталог;
  • l — ссылка;
  • p — pipe;
  • s — сокет.
-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
-print Показать найденное.
-print0 Путь к найденным объектам.
-exec <команда> {} ; Выполнить команду над найденным.
-ok Выдать запрос перед выполнением -exec.

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

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

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

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

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

1. Простой поиск по имени:

find / -name “file.txt”

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

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

find / -name “*.tmp”

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

3. Несколько условий. 

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

find . -name “sess_*” -a -name “*cd”

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

find . -name “sess_*” -o -name “*cd”

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

find . -regex ‘.*/(sess_.*cd)’

find . -regex ‘.*/(sess_.*|.*cd)’

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

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

find . ! -name “*.log”

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

Поиск по дате

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

find . -type f -mtime +60

* данная команда найдет файлы, которые менялись более 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

По типу

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

find . -type f

* 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 %pn’ | sort -r

* команда найдет все файлы в каталоге /data, добавит к имени дату модификации и отсортирует данные по имени. В итоге получаем, что файлы будут идти в порядке их изменения.

Лимит на количество выводимых результатов

Самый распространенный пример — вывести один файл, который последний раз был модифицирован. Берем пример с сортировкой и добавляем следующее:

find /data -type f -printf ‘%TY-%Tm-%Td %TT %pn’ | 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 . -name “*.tmp” | wc -l

5. Изменить права:

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:

crontab -e

И добавляем:

0 0 * * * /bin/find /tmp -mtime +14 -exec rm {} ;

* в данном примере мы удаляем все файлы и папки из каталога /tmp, которые старше 14 дней. Задание запускается каждый день в 00:00.
* полный путь к исполняемому файлу find смотрим командой which find — в разных UNIX системах он может располагаться в разных местах.


Download Article

The easiest way to locate files by name, partial name, or date at the command line


Download Article

  • Using Find: The Basics
  • |

  • Finding by Name or Partial Name
  • |

  • Finding by Time and Date
  • |

  • Finding by Size
  • |

  • Finding by Owner or Permissions
  • |

  • Combining Find Commands
  • |

  • Performing Actions on Found Files
  • |

  • Searching for Text in Files
  • |

  • Q&A

If you’re looking for a file on your Linux system, the find command makes it easy. You can use find to search for files by name, partial name, date, modification time, size, and more. If you know which directory the file is in, you can specify that directory in your find command. If not, you can search your entire Linux system starting with the root (/) directory. This wikiHow article will teach you how to use the find command in Linux to find any file, from files you downloaded to configuration files.

Things You Should Know

  • The basic syntax of find is find <starting directory> <options> <search terms>
  • You can use asterisks as wildcards if you don’t know the exact name of the file.
  • Use the -iname option to ignore case sensitivity when using find.
  1. Image titled Find a File in Linux Step 1

    1

    You’ll typically use the find command with the syntax find /path -type f -iname filename. You can use a variation of this command to find any file or directory on your Linux machine. We’ll break down the command into simple parts.

  2. Image titled Find a File in Linux Step 2

    2

    /path/to/file is the directory in which you want to search for the file. For example, to search the current directory, use . as the path. To search your entire Linux file system, use / as the path.

    Advertisement

  3. Image titled Find a File in Linux Step 3

    3

    -type indicates the type of file or directory you’re searching for. You’ll follow -type with a flag. In our example, we’re using the f flag. When searching for files, you’ll typically use any of these three flags:

    • f: This means “regular file,” which can be a text file, image, program, configuration file, executable, and basically any type of file (including hidden files).

      • Tip: -type f is the default for the find command. This means that if you’re looking for a file (not a directory or symbolic link), you can actually leave -type f out of the file command.
    • d: Searches for directories (folders).
    • l: Searches for symbolic links to other files.
    • You can search for multiple types by separating the letters with commas. For example, to find all files, directories, and symbolic links called “etc,” you’d use find / -type f,d,l -iname etc
  4. Image titled Find a File in Linux Step 4

    4

    -iname tells find to ignore case-sensitivity. This is important if you’re not 100% sure of the file’s name or case. However, if you want find to specifically match the case you type, replace -iname with -name, which is case-sensitive.[1]

  5. Image titled Find a File in Linux Step 5

    5

    filename is the name of the file you’re looking for. If you know the exact name of the file, you’ll type it completely. If not, you can use wildcards anywhere in your search term.

    • For example, to find all configuration files on your computer, you might use find / -type f -iname "*.conf". This returns the names of files ending with .conf.
  6. Advertisement

  1. Image titled Find a File in Linux Step 6

    1

    Use find /path -iname filename to search for a file by exact name. If you know the exact name and directory of the file, you’d use this command to find it.

  2. Image titled Find a File in Linux Step 7

    2

    Use the wildcard character * to search for anything that matches the part of the query. The wildcard * character is useful for finding files when you don’t know the full name. This can help you find files with specific file extensions (e.g., .pl or .c). Some helpful examples:

    • find /home/pat -iname "*.conf"

      • This will return all of the .conf files in Pat’s user directory and subdirectories.
    • find / -type d -iname "*lib*"

      • This command finds all directories on the Linux filesystem containing the string “lib.”
  3. Image titled Find a File in Linux Step 8

    3

    Make your search results easier to manage with the less command. If you’re getting lots of results, it can be difficult to sift through them. By piping the results to the less command, you can scroll through them easily. For example:

    • find /home/pat -iname "*.conf" | less
  4. Advertisement

  1. Image titled Find a File in Linux Step 9

    1

    Use the -mtime option to find files by modification date (in days). Use this option when you want to find files last modified a certain number of days ago (or between two day ranges). Some examples:

    • find /home/pat -iname "*.txt " -mtime -2

      • This command will find all files ending with .txt in the directory /home/pat modified in the last two days.
    • Place a + before the number of days to indicate “longer than x days ago, or a to indicate fewer than x days ago .[2]
      For example:

      • find . -mtime +90 : This command will display all files in the current directory that were modified more than 90 days ago.
      • find /home/pat -iname "*test*" -mtime -90 : This command will list all files in /home/pat with “test” in the name edited in the past 90 days.
    • If you want to find files modified by minutes instead of days, use -mmin instead. For example, to find all files in the current directory modified in the last 10 minutes, you’d use find . -type f -mmin -10.
  2. Image titled Find a File in Linux Step 10

    2

    Use -atime and -ctime to find files by the date last accessed or date created. Replace -mtime with -atime to search by the last date accessed (opened), or -ctime to search by the day the file was created (e.g., 15 days ago, or more than 90 days ago.

    • If you’d rather search by minutes instead of days, replace -atime with -amin and -ctime with -cmin.
  3. Image titled Find a File in Linux Step 11

    3

    Find files between two timestamps. To search for files between two specific dates and times, use the -newermt option. You’ll need to use this option twice in your command—one for the start date of your search, and another for the end date. Here’s how it will look:

    • find / -type f -newermt "2022-12-02 11:00:00" ! -newermt "2023-2-08 12:00:00"

      • This command will find all files on the Linux system with timestamps between 12/02/2022 at 11:00 AM and 2/08/2023 at 12PM.
  4. Advertisement

  1. Image titled 690519 6 1

    Filter your search results by size. If you have lots of files with similar names, but know the size you are looking for, you can filter results by size.

    • find / -size +50M -iname filename

      • This example will return results that are 50 megabytes or larger.
      • You can use + or - to search for greater or lesser sizes.
      • Omitting the + or - will search for files exactly the specified size.
      • You can filter by bytes (c), kilobytes (k), megabytes (M), gigabytes (G), or 512-byte blocks (b).
  1. Image titled 690519 8 1

    Use the -user, -group, and -perm options to find files by owner or permissions. If you are trying to find a specific file owned by a user, or files with certain permissions, you can narrow the search.

    • Examples:

      • find / -user pat -iname filename searches for files called filename owned by the user pat.
      • find / -group users -iname filename searches for files called filename in the users group.
      • find / -perm 777 -iname filename searches for files called filename with 777 permissions (no restrictions).
  2. Advertisement

  1. Image titled 690519 7 1

    Use boolean operators to combine search filters. You can use the -and, -or, and -not operators to combine different types of searches into one. For example:

    • find /travelphotos -type f -size +200k -not -iname "*2015*"
    • The command will find files in the “travelphotos” directory that are greater than 200 kb in size but do not have “2015” anywhere in the file name.
  1. Image titled 690519 9 1

    Combine commands to perform actions when files are located. You can combine find with other commands so that you can execute them on the files that are returned by the query. You can also use this feature to run the files that appear in find results. Separate the find command and the second command with the -exec flag, and then end the line with {} ;. For example:

    • find . -type f -perm 777 -exec chmod 755 {} ;
    • This will search the current directory (and all subdirectories) for files that have 777 permissions. It will then use the chmod command to change the permissions to 755.
  2. Advertisement

  1. Image titled 690519 14 1

    1

    Use the grep command to search for strings of text within files. If you are looking for a file that contains a certain phrase or string of characters, you can use the grep command. Here’s an example of a basic grep command:

    • grep -r -i "search query" /path/to/directory/
    • The -r flag sets the search to “recursive”, so it will search the current directory and all subdirectories for any file that contains the query string.
    • The -i flag indicates that the query is not case-sensitive. If you want to force the search to pay attention to case, omit the -i flag.
  2. Image titled 690519 15 1

    2

    Cut out the extra text. When you perform a grep search as above, you’ll see the file name along with the text with the matching query highlighted. You can hide the matching text and just display the file names and paths by including the following:

    • grep -r -i "search query" /path/to/directory/
  3. Image titled 690519 16 1

    3

    Hide error messages. The grep command will return an error when it tries to access folders without the correct permissions or runs into empty folders. You can send the error messages to /dev/null, which will hide them from the output.

    • grep -r -i "search query" /path/to/directory/ 2>/dev/null
  4. Advertisement

Add New Question

  • Question

    What does the ‘ls’ command do?

    Community Answer

    The ‘ls’ command lists all files in the current directory you are working in. To find out what directory you are working in, type ‘pwd’ (stands for “print working directory”).

  • Question

    Which command will display the last ten lines of a file?

    Community Answer

    You have to used tail command to display the last lines of a file, the command used is, “tail -n filename.” To display last 10 lines the command will be: tail -10 filename.

  • Question

    How can I find a file in the root directory if I’ve forgotten the name and the directory in which it was placed?

    Living Concrete

    Living Concrete

    Top Answerer

    You can try searching for a file extension, or checking places where files are commonly saved, such as your home directory. If it’s a text file, you can try using a recursive grep search (‘grep -R’) with text that you remember from the file as search criteria.

See more answers

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

References

About This Article

Article SummaryX

1. Open a command prompt.
2. Type / file -iname ″filename″
3. Replace ″filename″ with the file’s name.
4. Press Enter or Return.

Did this summary help you?

Thanks to all authors for creating a page that has been read 1,070,106 times.

Reader Success Stories

  • Ahmad El-Komey

    Ahmad El-Komey

    May 17, 2016

    “I needed a quick tutorial on how to search for files, given a piece of a name, using the terminal. This tutorial is…” more

Is this article up to date?

Image

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.

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

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.

[ Learn how to manage your Linux environment for success. ]

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

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.

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.

Добавить комментарий