Linux shell search in file

Search For Files In Bash

H ow do I search for file in Bash?

You can use the following commands to search for files in a bash shell:

  1. locate command – find files by name. It reads one or more databases created by updatedb and writes file names matching at least one of the PATTERNs to the screen, one per line. This may not contains file created within last 12-24 hrs.
  2. find command – search for files in a directory hierarchy in real time.

locate command in bash

To search a file called xorg.conf, enter:
locate xorg.conf
Sample outputs:

Instead of writing file names on scree, write the number of matching entries only, enter:
locate -c xorg.conf
Sample outputs:

  • 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

Ignore case matching (i.e. match foo.txt, FOO.TXT, foo.Txt and so on):
locate -i filename
Only find and limit search to one file at a time:
locate -n 1 filename
Only find and limit search to three files at a time:
locate -n 3 filename
To search for a file named exactly NAME (not *NAME*), use
locate -b ‘\FILENAME’
Find information about current databased created by the updatedb command:
locate -S
Sample outputs:

find command in bash

The basic syntax is as follows:
find /path/to/dir -name «filename»
In this example, find httpd.conf file in /etc directory:
find /etc -name «httpd.conf»
To find all headers file *.h in /nas/projects directory, enter:
find /nas/projects -name «*.h»
Please see our previous FAQs about find command which covers many find command examples:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

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 Files in Linux Using the Command Line

When you have to find a file in Linux, it’s sometimes not as easy as finding a file in another operating system. This is especially true if you are running Linux without a graphical user interface and need to rely on the command line. This article covers the basics of how to find a file in Linux using the CLI. The find command in Linux is used to find a file (or files) by recursively filtering objects in the file system based on a simple conditional mechanism. You can use the find command to search for a file or directory on your file system. By using the -exec flag ( find -exec ), files can be found and immediately processed within the same command.

Find a File in Linux by Name or Extension

Use find from the command line to locate a specific file by name or extension. The following example searches for *.err files in the /home/username/ directory and all sub-directories:

Using Common find Commands and Syntax to Find a File in Linux

find expressions take the following form:

  • The options attribute will control the find process’s behavior and optimization method.
  • The starting/path attribute will define the top-level directory where find begins filtering.
  • The expression attribute controls the tests that search the directory hierarchy to produce output.

Consider the following example command:

This command enables the maximum optimization level (-O3) and allows find to follow symbolic links ( -L ). find searches the entire directory tree beneath /var/www/ for files that end with .html .

Basic Examples

Command Description
find . -name testfile.txt Find a file called testfile.txt in current and sub-directories.
find /home -name *.jpg Find all .jpg files in the /home and sub-directories.
find . -type f -empty Find an empty file within the current directory.
find /home -user exampleuser -mtime -7 -iname «.db» Find all .db files (ignoring text case) modified in the last 7 days by a user named exampleuser.

Options and Optimization for find

The default configuration for find will ignore symbolic links (shortcut files). If you want find to follow and return symbolic links, you can add the -L option to the command, as shown in the example above.

find optimizes its filtering strategy to increase performance. Three user-selectable optimization levels are specified as -O1 , -O2 , and -O3 . The -O1 optimization is the default and forces find to filter based on filename before running all other tests.

Optimization at the -O2 level prioritizes file name filters, as in -O1 , and then runs all file-type filtering before proceeding with other more resource-intensive conditions. Level -O3 optimization allows find to perform the most severe optimization and reorders all tests based on their relative expense and the likelihood of their success.

Command Description
-O1 (Default) filter based on file name first.
-O2 File name first, then file type.
-O3 Allow find to automatically re-order the search based on efficient use of resources and likelihood of success.
-maxdepth X Search current directory as well as all sub-directories X levels deep.
-iname Search without regard for text case.
-not Return only results that do not match the test case.
-type f Search for files.
-type d Search for directories.

Find a File in Linux by Modification Time

The find command contains the ability to filter a directory hierarchy based on when the file was last modified:

The first command returns a list of all files in the entire file system that end with the characters conf and modified in the last seven days. The second command filters exampleuser user’s home directory for files with names that end with the characters conf and modified in the previous three days.

Use grep to Find a File in Linux Based on Content

The find command can only filter the directory hierarchy based on a file’s name and metadata. If you need to search based on the file’s content, use a tool like grep . Consider the following example:

This searches every object in the current directory hierarchy ( . ) that is a file ( -type f ) and then runs the command grep «example» for every file that satisfies the conditions. The files that match are printed on the screen ( -print ). The curly braces ( <> ) are a placeholder for the find match results. The <> are enclosed in single quotes ( ‘ ) to avoid handing grep a malformed file name. The -exec command is terminated with a semicolon ( ; ), which should be escaped ( \; ) to avoid interpretation by the shell.

How to Find and Process a File in Linux

The -exec option runs commands against every object that matches the find expression. Consider the following example:

This filters every object in the current hierarchy ( . ) for files named rc.conf and runs the chmod o+r command to modify the find results’ file permissions.

The commands run with the -exec are executed in the find process’s root directory. Use -execdir to perform the specified command in the directory where the match resides. This may alleviate security concerns and produce a more desirable performance for some operations.

The -exec or -execdir options run without further prompts. If you prefer to be prompted before action is taken, replace -exec with -ok or -execdir with -okdir .

How to Find and Delete a File in Linux

To delete the files that end up matching your search, you can add -delete at the end of the expression. Do this only when you are positive the results will only match the files you wish to delete.

In the following example, find locates all files in the hierarchy starting at the current directory and fully recursing into the directory tree. In this example, find will delete all files that end with the characters .err :

More Information

You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

This page was originally published on Monday, October 25, 2010.

Источник

Команда 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 может сильно облегчить жизнь системному администратору, а лучший способ овладеть ей – больше практиковаться.

Источник

Читайте также:  No device driver were found windows 10
Оцените статью