Locating files in linux

Поиск файлов в Linux при помощи команды locate

Только что я понял, что я ни разу не писал об одной из моих любимых программ, используемых в командной оболочке Linux: locate .

Эта программа принимает в качестве параметра имя файла (или часть имени) и моментально выводит список путей до этого файла в файловой системе; альтернативой этой программе является find , но разница между ними заключается в том, что find производит поиск по файловой системе и требуется значительный период времени для получения результата, а отличие в работе этих программ состоит в том, что locate использует собственную базу данных для хранения имен файлов в то время, как find исследует директории в поисках заданного параметром командной строки имени файла.

База данных locate mlocate.db

Для получения результатов, соответствующих действительности, вам необходимо поддерживать в обновленном состоянии базу данных со списком имен файлов. Операционная система может быть настроена таким образом, что обновление будет выполняться автоматически как задача cron . Например, в моей операционной системе Ubuntu 12.04 эта задача описана в файле /etc/cron.daily/mlocate и выполняется ежедневно.

Если в вашем дистрибутиве обновление по умолчанию отключено, можно обновить базу данных вручную при помощи команды sudo updatedb (требуются права пользователя root); это очень удобно в том случае, когда вы только что установили пакеты с программным обеспечением и хотите найти какой-либо файл, так как время, уходящее на обновление базы данных при помощи updatedb , всегда меньше времени на поиск файлов по всей файловой системе при помощи find .

Ниже приведено содержимое файла конфигурации в моей системе:

Использование locate

Теперь, когда мы настроили и обновили базу данных, мы можем начать использовать команду locate (в рамках обычной пользовательской учетной записи или учетной записи пользователя root — на ваше усмотрение); ниже приведено несколько примеров использования:

Это очень полезная команда в том случае, когда вам нужно внести изменения в файл конфигурации php, но вы не можете вспомнить, где расположен файл php.ini.

Скрытие сообщений об ошибках

В результате будут выведены первые 10 файлов с расширением .php.

Подсчет количества результатов поиска

Независимый от регистра поиск

Информация о базе данных

Заключение

Эта команда помогала мне множество раз в различных ситуациях, поэтому она установлена на каждом сервере или настольном компьютере, который я использую. Я не стал включать раздел об установке программы в эту короткую статью по той причине, что locate доступна в любом дистрибутиве Linux, обычно в пакете с названием mlocate , поэтому вы можете использовать ваш менеджер пакетов для ее установки, и еще я уверен, что вы полюбите ее.

Источник

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.

Читайте также:  Windows edb как уменьшить

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.

Источник

Linux: Finding and Locating files with find command part # 1

Many newcomers find it difficult use the find command at shell prompt under Linux / *BSD or Solairs UNIX oses. Find is nifty tool on remote server where UNIX admin can find out lot of information too. Desktop users may find handy GNOME Search tool as a utility for finding files on system. Find command can perform a search based on a variety of search constraints. It searches through one or more directory tree(s) of a filesystem, locating files based on some user-specified criteria. By default, find returns all files below the current working directory. Further, find allows the user to specify an action to be taken on each matched file. Thus, it is an extremely powerful program for applying actions to many files. It also supports regexp matching.

GNOME Search Tool GUI Program

GNOME Search Tool is a utility for finding files on your system. To perform a basic search, you can type a filename or a partial filename, with or without wildcards. You can start this program from menus or by typing following command at shell prompt:
$ gnome-search-tool &
Internally GNOME Search Tool uses the find, grep, and locate UNIX commands. The case sensitivity of the search depends on your operating system. For example, on Linux, the find, grep, and locate commands support the -i option, so all searches are case-insensitive.

Find command syntax

  • search-path : Define search path (default current directory). For example search in /home directory.
  • file-names-to-search : Name of the file you wish to find. For example all c files (*.c)
  • action-to-take : Action can be print file name, delete files etc. Default action is print file names.

Find command examples

Let us try out some examples.

Finding files and printing their full name

You wish to find out all *.c (all c source code) files located under /home directory, enter:
$ find /home -name «*.c»

You would like to find httpd.conf file location:
$ find / -name httpd.conf

Finding all files owned by a user

Find out all files owned by user vivek:
# find / -user vivek

  • 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

Find out all *.sh owned by user vivek:
# find / -user vivek -name «*.sh»

Finding files according to date and time

Files not accessed in a time period – It is useful to find out files that have or have not been accessed within a specified number of days. Following command prints all files not accessed in the last 7 days:
# find /home -atime +7

  • -atime +7: All files that were last accessed more than 7 days ago
  • -atime 7: All files that were last accessed exactly 7 days ago
  • -atime -7: All files that were last accessed less than7 days ago

Finding files modified within a specified time – Display list of all files in /home directory that were not last modified less than then days ago.
# find /home -mtime -7

Finding newer (more recently) modified files

Use -newer option to find out if file was modified more recently than given file.
# find /etc/apache-perl -newer /etc/apache-perl/httpd.conf

Finding the most recent version of file

It is common practice before modifying the file is copied to somewhere in system. For example whenever I modify web server httpd.conf file I first make backup. Now I don’t remember whether I had modified the /backup.conf/httpd.conf or /etc/apache-perl/httpd.conf. You can use the find command as follows (tip you can also use ls -l command):
find / -name httpd.conf -newer /etc/apache-perl/httpd.conf

Locate command

The locate command is often the simplest and quickest way to find the locations of files and directories on Linux and other Unix-like operating systems.

For example, the following command uses the star wildcard to display all files on the system that have the .c filename extension:
# locate «*.c»

Источник

Читайте также:  Unigram для windows 10
Оцените статью