- UNIX Find A File Command
- Syntax
- Examples – find command
- To list only files and avoid all directories
- Search all directories
- Execute command on all files
- Search file for specific sizes
- Say hello to locate command
- How to Find a File in Linux Using the Command Line
- The ‘find’ command offers powerful options to hone your search
- What to Know
- Use the ‘find’ Command to Locate a File in Linux
- Search Location Shortcuts
- Expressions
- Example Usage of the Find Command
- How to Find Files Accessed More Than a Certain Number of Days Ago
- How to Find Empty Files and Folders
- How to Find All of the Executable Files
- How to Find All of the Readable Files
- Patterns
- How to Send Output from the Find Command to a File
- How to Find and Execute a Command Against a File
- Команда find в Linux – мощный инструмент сисадмина
- Поиск по имени
- Поиск по типу файла
- Поиск по размеру файла
- Единицы измерения файлов:
- Поиск пустых файлов и каталогов
- Поиск времени изменения
- Поиск по времени доступа
- Поиск по имени пользователя
- Поиск по набору разрешений
- Операторы
- Действия
- -delete
- Заключение
UNIX Find A File Command
I am a new Sun Solaris UNIX user in our Lab. I would like to know more about finding files from the shell prompt. How do I find a file under UNIX operating systems using bash or ksh shell?
You need to use find command which is used to search files and directories under Linux and Unix like operating systems. You can specify criteria while search files. If no criteria is set, it will returns all files below the current working directory. The find command also supports regex matching and other advanced options.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | find/locate |
Est. reading time | 5m |
Another option is locate command. It find files by name. The locate command reads databases prepared by updatedb and displays file names matching at least one of the PATTERNs to screen.
Syntax
The syntax is:
find /dir/to/search -name «file-to-search»
find /dir/to/search -name «file-to-search» -print
find /dir/to/search -name «file-to-search» -ls
find /dir/to/search -name «regex» -print
- 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 ➔
Examples – find command
To find all perl (*.pl) files in current directory:
$ find . -name ‘*.pl’
The . represent the current directory and the -name option specifies all pl (perl) files. The quotes avoid the shell expansion and it is necessary when you want to use wild card based search (without quotes the shell would replace *.pl with the list of files in the current directory).
To list only files and avoid all directories
The following command will only list files and will exclude directories, special files, pipes, symbolic links etc:
$ find . -type f -name ‘*.pl’
Sample outputs:
Fig.01: Find command in action
Search all directories
Search file called httpd.conf in all directories:
$ find / -type f -name httpd.conf
Generally this is a bad idea to look for files. This can take a considerable amount of time. It is recommended that you specify the directory name. For example look httpd.conf in /usr/local directory:
$ find /usr/local -type f -name httpd.conf
You may need to run it as root:
$ sudo find / -type f -name httpd.conf
Execute command on all files
Run ls -l command on all *.c files to get extended information :
$ find . -name «*.c» -type f -exec ls -l <> \;
OR
$ find . -name «*.c» -type f -ls
You can run almost all UNIX command on file. For example, modify all permissions of all files to 0700 only in
/code directory:
$ find
/code -exec chmod 0700 <> \;
Search for all files owned by a user called payal:
$ find . -user
$ find . -user payal
Search file for specific sizes
Search for 650 megabytes or above size file in
/Downloads/ dir:
$ find
/Downloads/ -size +650M
## gigabytes ##
$ find
/Downloads/ -size +1G
## kilobytes ##
$ find
/Downloads/ -size +1024k
Read find command man page for detailed information:
$ man find
Say hello to locate command
To search for a file named exactly foo (not *foo*), type:
$ locate -b ‘\foo’
Just search for file name matching yum.conf, type:
$ locate yum.conf
To search for a file named exactly yum.conf (not *yum.conf* anywhere in / path), type:
$ locate -b ‘\yum.conf’
Sample outputs:
Fig.02: locate command in action on Linux based system.
Recommended readings:
See our previous articles about finding files:
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How to Find a File in Linux Using the Command Line
The ‘find’ command offers powerful options to hone your search
What to Know
- The command used to search for files is called find. The basic syntax of the find command is as follows: find [filename].
- After find, use a shortcut to specify the directory: «.» for nested folders; «/» for the entire file system; »
» for the active user’s home directory.
This article explains what the Linux find command is, offers search location shortcuts, common expressions, example usages, patterns, how to send outputs from the find command to a file, and how to find and execute a command against a file.
Use the ‘find’ Command to Locate a File in Linux
The command used to search for files is called find.
The basic syntax of the find command is as follows:
The currently active path marks the search location, by default. To search the entire drive, type the following:
If, however, you want to search the folder you are currently in, use the following syntax:
When you search by name across the entire drive, use the following syntax:
- The first part of the find command is the find command.
- The second part is where to start searching from.
- The next part is an expression that determines what to find.
- The last part is the name of the file to find.
To access the shell (sometimes called the terminal window) in most distributions, click the relevant icon or press Ctrl+Alt+T.
Search Location Shortcuts
The first argument after the find command is the location you wish to search. Although you may specify a specific directory, you can use a metacharacter to serve as a substitute. The three metacharacters that work with this command include:
- Period (.): Specifies the current and all nested folders.
- Forward Slash (/): Specifies the entire filesystem.
- Tilde (
): Specifies the active user’s home directory.
Searching the entire filesystem may generate access-denied errors. Run the command with elevated privileges (by using the sudo command) if you need to search in places your standard account normally cannot access.
Expressions
The most common expression you will use is -name, which searches for the name of a file or folder.
There are, however, other expressions you can use:
- -amin n: The file was last accessed +/- n minutes ago, depending on how you enter the time.
- -anewer: Takes another file as reference to find any files that were accessed more recently and the reference file.
- -atime n: The file was last accessed more/fewer than n days ago, depending on the how you enter the target time (n).
- -cmin n: The file was last changed n minutes ago, depending on how you enter the target time (n).
- —cnewer: Takes another file as reference to find any files that were accessed more recently and the reference file.
- -ctime n: The file was last accessed more/fewer than n days ago, depending on the how you enter the target time (n).
- -empty: The file is empty.
- —executable: The file is executable.
- -false: Always false.
- -fstype type: The file is on the specified file system.
- -gid n: The file belongs to group with the ID n.
- -group groupname: The file belongs to the named group.
- -ilname pattern: Search for a symbolic link but ignore the case.
- -iname pattern: Search for a file but ignore the case.
- -inum n: Search for a file with the specified inode.
- -ipath path: Search for a path but ignore the case.
- -iregex expression: Search for an expression but ignore the case.
- -links n: Search for a file with the specified number of links.
- -lname name: Search for a symbolic link.
- -mmin n: The file was last accessed +/- n minutes ago, depending on how you enter the time.
- -mtime n: The file was last accessed more/fewer than n days ago, depending on the how you enter the target time (n).
- -name name: Search for a file with the specified name.
- -newer name: Search for a file edited more recently than the reference file given.
- -nogroup: Search for a file with no group id.
- -nouser: Search for a file with no user attached to it.
- -path path: Search for a path.
- —readable: Find files that are readable.
- -regex pattern: Search for files matching a regular expression.
- -type type: Search for a particular type. Type options include:
- -type d: Directoris
- -type f: Files
- -type l: Symlinks
- -uid uid: The file numeric user id is the same as the uid.
- -user name: The file is owned by the user that is specified.
- -writable: Search for files that can be written to.
Example Usage of the Find Command
Here are some of the ways you can use the find command.
How to Find Files Accessed More Than a Certain Number of Days Ago
To find all the files within your home folder accessed more than 100 days ago:
How to Find Empty Files and Folders
To find all the empty files and folders in your system:
How to Find All of the Executable Files
To find all the executable files on your computer:
How to Find All of the Readable Files
To find all the files that are readable:
Patterns
When you search for a file, you can use a pattern. For example, search for all files with the extension mp3:
Depending on the shell you’re using, you may need to escape the asterisk. If you run the command and don’t get the results you’re expecting, try quoting the entire pattern to escape the asterisk, like so: find / -name ‘*.mp3’
How to Send Output from the Find Command to a File
The main problem with the find command is that it can sometimes return too many results to look at in one go. Pipe the output to the tail command, or output the lines to a file as follows:
find / -name *.mp3 -fprint nameoffiletoprintto
How to Find and Execute a Command Against a File
To search for and edit a file at the same time, type:
The above command searches for a file called filename and then runs the nano editor for the file that it finds.
Nano is the name of a command, not an exact part of this syntax.
Источник
Команда 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 может сильно облегчить жизнь системному администратору, а лучший способ овладеть ей – больше практиковаться.
Источник