- Поиск в Linux с помощью команды find
- Общий синтаксис
- Описание опций
- Примеры использования find
- Поиск файла по имени
- Поиск по дате
- По типу
- Поиск по правам доступа
- Поиск файла по содержимому
- С сортировкой по дате модификации
- Лимит на количество выводимых результатов
- Поиск с действием (exec)
- Чистка по расписанию
- How to find a folder in Linux using the command line
- Command to find a folder in Linux
- How to find folder on Linux using find command
- Finding a folder named Documents
- How to search for case incentive folder names
- How to search a folder named /etc/ in the root (/) file system
- How to hide “Permission denied error messages” when using find command
- How do I find a directory called python.projects?
- Understanding find command options
- Search folder in Linux using locate command
- Conclusion
- How To Find a Directory On Linux Based System
- How to find a directory on Linux
- Linux find directory command
- Finding a directory
- Dealing with “Permission denied error messages” on Linux
- How to find a directory named Documents on Linux?
- Getting a detailed list of files/dirs
- How do I list only directories?
- How do I perform a case insensitive search?
- How do I find a directory called project.images?
- A note about locate command
Поиск в 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 a folder in Linux using the command line
Command to find a folder in Linux
- find command – Search for files and folder in a directory hierarchy
- locate command – Find files and folders by name using prebuilt database/index
How to find folder on Linux using find command
The syntax is:
find /where/to/look/up/ criteria action
find /folder/path/to/look/up/ criteria action
find /folder/path/ -name «folder-name-here»
find /search/path/ -name «folder-name-here» -print
find /search/path/ -name «folder-name-here» -ls
find /folder/ -name «pattern»
Finding a folder named Documents
To find a folder named “Documents” in your home directory ($HOME i.e. /home/vivek/ home directory), run:
find $HOME -type d -name «Documents»
OR
find
-type d -name «Documents»
OR
find /home/vivek/ -type d -name «Documents»
find command in action on Linux
How to search for case incentive folder names
You can force find command interpret upper and lowercase letters as being the same. For example match Documents, DOCUMENTS, DocuMEnts and so on by passing the -iname option:
find $HOME -type d -iname «Documents»
OR
find
-type d -iname «Documents»
OR
find /home/vivek/ -type d -iname «Documents»
Sample outputs:
How to search a folder named /etc/ in the root (/) file system
When searching / (root) file system, you need to run the find command as root user:
# find / -type d -name «etc»
OR
$ sudo find / -type d -name «etc»
OR
$ sudo find / -type d -iname «etc»
How to hide “Permission denied error messages” when using find command
The find will show an error message for each directory/file on which you don’t have read permission. To avoid those messages, append 2>/dev/null at the end of each find command:
$ find /where/to/look/ criteria action 2>/dev/null
$ sudo find / -type d -iname «etc» 2>/dev/null
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
How do I find a directory called python.projects?
Try:
find / -type d -iname «python.projects» -ls
OR
find / -type d -name «python.projects» -ls
It is also possible to use the bash shell wild cards, run:
find / -type d -name «python.*»
sudo find / -type d -name «?ython.*»
Understanding find command options
- -name : Base of file name (the path with the leading directories removed) matches shell pattern.
- -iname : Perform a case insensitive search for given pattern
- -print : Print the full file name on the standard output (usually screen), followed by a newline.
- -ls : Display current file in ls -dils format on standard output i.e. your screen.
- -type d : Only list folders or directories.
- -type f : Only list files.
Search folder in Linux using locate command
To search for a folder named exactly dir1 (not *dir1*), type:
$ locate -b ‘\dir1’
$ locate -b ‘\folder2’
Just search for file name matching Pictures, type:
$ locate Pictures
For more info see “UNIX Find A File Command“.
Conclusion
In this tutorial, you learned how to find a folder on the Linux system using find and locate commands. For more info see gnu find command help page here.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How To Find a Directory On Linux Based System
I just switched from MS-Windows server admin to Debian Linux server system administration roles. I need to find a directory called project.images. I was also told that the locate command is the simplest and quickest way to find the locations of files and directories on Linux. But the locate command is not working out for me. How do I find project.images directory using command-line options only?
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | find command on Linux or macOS/Unix |
Est. reading time | 5m |
You need to use find command. It is used to locate files on Linux or Unix-like system. The locate command will search through a prebuilt database of files generated by updatedb.
The find command will search live file-system for files that match the search criteria.
How to find a directory on Linux
The find command syntax is:
find /where/to/look/up criteria action
find /dir/path/look/up criteria action
find /dir/path/look/up -name «dir-name-here»
find /dir/path/look/up -name «pattern»
find /dir/path/look/up -name «dir-name-here» -print
find /dir/path/look/up -name «dir-name-here»
find / -name «dir-name-here»
find / -type d -name «dir-name-here»
find / -type d -name «dir-name-here» 2>/dev/null
Linux find directory command
The following example will show all files in the current directory and all subdirectories:
Finding a directory
To find a directory called apt in / (root) file system, enter:
Alert: When searching / (root) file system, you need to run the find command as root user.
Dealing with “Permission denied error messages” on Linux
Find will show an error message for each directory/file on which you don’t have read permission
How to find a directory named Documents on Linux?
Type the following command to search for Documents directory in your $HOME dir:
$ find $HOME -type d -name Documents
Sample outputs:
Getting a detailed list of files/dirs
Pass the -ls to list current file in ls command output format:
How do I list only directories?
Just find directories and skip file names pass the -type d option as follows:
How do I perform a case insensitive search?
Replace -name option with -iname as follows:
The patterns ‘apt’ match the directory names ‘apt’, ‘APT’, ‘Apt’, ‘apT’, etc.
How do I find a directory called project.images?
Type any one of the following command:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
A note about locate command
See also
- All find command examples from our /faq/ sections.
- Find command man page
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
Why don’t you run updatedb and then locate and again you’ll have “simplest and quickest way to find the locations of files and directories on Linux”.
updatedb will update your database.
That only helps for semi-permanent files since it only checks periodically to update the updatedb database. For files that were created recently it will not be found.
Find is a great tool that i use a lot.
You could have talk about the -exec switch wich allows you to process the outpout. ie : find and delete all file in ./ that haven’t been modified since 90 day:
Anyway, great job on this website, keep it on!
I have to second that updatedb is the way to go for a novice linux user. No worries about syntax and whatnot. Its also very useful for when you need to do multiple scans since you only traverse the filesystem once.
In regards to -exec, you should be using -execdir when available due to some security implications… and the above rm -rf is somewhat dangerous since find by default traverses from the top down. Delete would be a much safer (and faster!!) operation than-exec rm.
I have to agree with your update, rm -Rf is maybe too dangerons to use for novice users.
I did not know -execdir wich seems to be very usefull.
Thank you for that update =)
Great article. so useful. since I don’t have root, I get very verbose “no permission” output that is useless and I have to find the actual location through all the muck. Is there a way to only print found paths? Thanks so much for this article!
All those “no permission” messages should be on stderr while the information you want is on stdout. Both stderr and stdout default to printing on the controlling terminal. Tacking “> stdoutfile” on the end of the command would separate them, leaving all the unwanted noise on the terminal and putting the good stuff in stdoutfile. It would make more sense to redirect stderr to /dev/null (throwing it away) and leaving the useful output on the controlling terminal, but that would require finding the instructions for redirecting stderr in the shell docs (again).
To avoid seeing stderr messages, just use something like this:
Источник