- 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
- Команда find в Linux – мощный инструмент сисадмина
- Поиск по имени
- Поиск по типу файла
- Поиск по размеру файла
- Единицы измерения файлов:
- Поиск пустых файлов и каталогов
- Поиск времени изменения
- Поиск по времени доступа
- Поиск по имени пользователя
- Поиск по набору разрешений
- Операторы
- Действия
- -delete
- Заключение
- 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
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
Источник
Команда 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 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:
Источник