Using locate in linux

Команда locate в Linux

Одна из самых распространенных операций при работе в Linux — это поиск файлов и каталогов. В системах Linux есть несколько команд, которые позволяют искать файлы, причем поиск и определение местоположения являются наиболее часто используемыми.

Команда locate — это самый быстрый и простой способ поиска файлов и каталогов по их именам.

В этой статье мы объясним, как использовать команду locate .

Установка locate (команда locate не найдена)

В зависимости от дистрибутива и того, как была подготовлена система, пакет locate может быть предварительно установлен или не установлен в вашей системе Linux.

Чтобы проверить, установлена ли утилита locate , откройте терминал, введите locate и нажмите Enter . Если пакет установлен, система отобразит locate: no pattern to search for specified . В противном случае вы увидите что-то вроде locate command not found .

Если locate не установлен, вы можете легко установить его с помощью диспетчера пакетов вашего дистрибутива.

Установите locate на Ubuntu и Debian

Установить locate на CentOS и Fedora

Как locate работу

Команда locate выполняет поиск заданного шаблона в файле базы данных, созданном командой updatedb . Найденные результаты отображаются на экране по одному в строке.

Во время установки пакета mlocate создается задание cron, которое запускает команду updatedb каждые 24 часа. Это гарантирует регулярное обновление базы данных. Для получения дополнительной информации о задании cron проверьте файл /etc/cron.daily/mlocate .

Базу данных можно обновить вручную, запустив updatedb от имени пользователя root или пользователя с привилегиями sudo:

Процесс обновления займет некоторое время, в зависимости от количества файлов и каталогов, а также скорости вашей системы.

Файлы, созданные после обновления базы данных, не будут отображаться в результатах поиска.

По сравнению с более мощной командой find которая выполняет поиск в файловой системе, команда locate работает намного быстрее, но не имеет многих функций и может выполнять поиск только по имени файла.

Как использовать команду locate

Синтаксис команды locate следующий:

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

Например, чтобы найти файл с именем .bashrc , введите:

Вывод будет включать имена всех файлов, содержащих в своих именах строку .bashrc :

Файл /root/.bashrc не будет показан, потому что мы /root/.bashrc команду как обычный пользователь, у которого нет прав доступа к каталогу /root .

Если список результатов длинный, для лучшей читаемости вы можете направить вывод в команду less :

Команда locate также принимает шаблоны, содержащие символы подстановки, такие как подстановочный знак * . Если в шаблоне нет дополнительных символов, команда ищет *PATTERN* . Поэтому в предыдущем примере отображались все файлы, содержащие в своем имени шаблон поиска.

Подстановочный знак — это символ, используемый для обозначения нуля, одного или нескольких символов. Например, чтобы найти все файлы .md в системе, вы должны ввести:

Чтобы ограничить результаты поиска, используйте параметр -n после которого укажите количество результатов, которые вы хотите отобразить. Следующая команда .py поиск всех файлов .py и отобразит только 10 результатов:

По умолчанию locate выполняет поиск с учетом регистра. Параметр -i ( —ignore-case ) указывает locate игнорировать регистр и запускать поиск без —ignore-case регистра.

Чтобы отобразить количество всех совпадающих записей, используйте параметр -c ( —count ). Следующая команда вернет количество всех файлов, содержащих .bashrc в своих именах:

По умолчанию locate не проверяет, существуют ли еще найденные файлы в файловой системе. Если вы удалили файл после последнего обновления базы данных, и если файл соответствует шаблону поиска, он будет включен в результаты поиска.

Читайте также:  Как открыть при запуске компьютера командную строку компьютер windows

Чтобы отображать только имена файлов, которые существуют на момент запуска locate , используйте параметр -e ( —existing ). Например, следующее будет возвращать только существующие файлы .json :

Если вам нужно выполнить более сложный поиск, используйте параметр -r ( —regexp ), который позволяет вам искать, используя базовое регулярное выражение вместо шаблонов. Этот параметр можно указывать несколько раз.
Например, чтобы найти все файлы .mp4 и .avi в вашей системе и игнорировать регистр, вы должны запустить:

Выводы

Команда locate ищет в файловой системе файлы и каталоги, имена которых соответствуют заданному шаблону. Синтаксис команды легко запомнить, а результаты отображаются практически мгновенно.

Для получения дополнительной информации обо всех доступных параметрах команды locate введите команду man locate в вашем терминале.

Если у вас есть вопросы, не стесняйтесь оставлять комментарии.

Источник

How to Use Find and Locate Commands In Linux: A Beginner’s Guide

Do you want to know how to perform searches on a Linux computer or server? Then you’ve come to the right place!

In this article, we’ll talk about the Linux find and locate commands, which will help you to look for any file on your machine.

Why Use Find and Locate Commands in Linux?

New Linux users often claim that they get confused about the location of their files on a server. This might be because most people are used to operating Windows or macOS, which have more clear-cut and user-friendly directory layouts.

While there is some truth to this, Linux gives users more options on how to search for files using certain commands. Besides searching based on common filters, you are also able to find files by user permissions, size, timestamps, and so on.

What’s great, once you understand the commands, searching for files on your Linux platform is strikingly easy.

To do that, we’ll utilize the find and locate commands in Linux.

An important thing to note is that we will be using Ubuntu VPS in this guide. That being said, the steps should also work for Debian, CentOS, or any other distribution of Linux. If you don’t know how to connect to VPS, you can follow this guide before proceeding further.

Using the Find Command in Linux

First, let us explain the find command and how to use it.

The Basic Syntax

The most popular command to find and filter files on Linux is find. The basic syntax is as follows:

It starts with the keyword find, which alerts Linux that whatever follows after will be used to find your file. The argument is the origin point of where you want to start the search. It can be replaced with several arguments, including:

  • / (slash) — search the whole system.
  • . (dot) — search from the folder you’re currently working on (current directory).

(tilde) — to search from your home folder.

In order to find the current directory you are in, use the pwd command.

The second argument is dedicated to your file. This could be the file’s name, type, date of creation, etc. The third argument is where you will specify the relevant search term.

Ways to Utilize find Command

Let’s take a look at various options Linux provides its users:

Searching by Name

Of course, the most common method to look for a file is using its name. To run a simple search query using the name of the file, use the find command like this:

We used the -name option, and searched for a file called my-file. Note that we started the search in our current directory by using the . (dot) argument.

Keep in mind that the -name argument looks for case-sensitive terms in Linux. If you know the name of the file, but are not sure about its case-sensitivity, use the following find command:

You can also search for all files without a certain keyword in their name. There are two ways to do this. The first method involves using the –not keyword in the following manner:

Second, we can use the exclamation symbol (!). However, it has to be preceded by the escape identifier (\) to let Linux know that this is the part of the find command.

You can look for multiple files with a common format like .txt as well:

This will list down all the text files starting with the current folder.

Lastly, if you want to find a certain file by name and remove it, use the -delete argument after the file name:

Searching by Type

Linux allows users to list all information based on their types. There are several filters that you can use:

  • d – directory or folder
  • f – normal file
  • l – symbolic link
  • c – character devices
  • b – block devices

A simple example of using a file type can be seen below:

This will list all of the current directories in your system since we searched from our root directory with the / (slash) symbol.

You can also combine the –type and -name options to narrow down your searches further:

This will look for files named my-file, excluding directories or links.

Searching by Time

If you want to search for files based on when they were accessed and modification time footprints. Linux keeps track of the files using these three timestamps.

  • Access Time (-atime) – when the file was either read or written into.
  • Modification Time (-mtime) – when the file was modified.
  • Change Time (-ctime) – when the file’s meta-data was updated.

This option has to be used with a number that specifies how many days passed since the file was accessed, modified or changed:

This command will show all files that were accessed a day ago starting from your current time.

We can narrow down our queries even more by adding plus (+) and minus (–) signs preceding the number of days. For instance:

It lists down all the files that have a modification time of more than two days ago.

To find all files whose meta-data was updated less than a day ago, run the following:

While not often used, there are some additional arguments that are also related to timed-searches. The -mmin argument looks for modified files on a minute basis. It can be used like this:

Also, we have the -newer argument, which can be used to compare the age of two or more files and display the newer one.

What you’ll get are all of the files that are more recently modified than your file.

Searching by Size

Linux lets you search for files based on their sizes. The syntax for searching files by size is:

You can specify the following size units:

  • c – bytes
  • k – kilobytes
  • M – megabytes
  • G – gigabytes
  • b – 512-byte chunks

A simple example of how to use the find command for file sizes is as follows:

Here we search for all of the files in your system that are exactly 10 megabytes. Just like when searching based on time, you can filter your searches further using the plus and minus signs:

It will display all the files that are more than five gigabytes in size.

Searching by Ownership

Linux gives you the ability to narrow down your searches based on file ownership. To find files of a certain owner, the following command should be executed:

The script will return a list of all files that the user named john owns. Similar to usernames, we can also find files through group names:

Searching by Permissions

Users can search for files based on file permissions using -perm option. For example:

In Linux, 644 corresponds to read and write permission. That means this command will look for all the files that have only read and write permissions. You can play around with this option further:

With an addition of a dash symbol, it will return with all the files that have at least 644 permission.

Feel free to read more on permissions and various codes corresponding to other Linux permissions.

Other Useful Options

There are other useful options that you should remember.

For example, to look for empty files and folders on your system, use the following:

Similarly, to look for all the executables saved on your drive, utilize the -exec option:

To look for readable files, you can run the following command:

As you can see, there is a ton of options at hand for users to tailor their queries as they wish. Let us look at the other command which can be used to locate files in Linux.

Using Locate Command in Linux

The locate command is a useful alternative, as it is faster than the find command when performing searches. That’s because the former only scans your Linux database instead of the whole system. Furthermore, the syntax is relatively easier to write.

How to Install locate Package

By default, Linux does not come with the locate command pre-installed. To get the package, run the following commands one after another:

The Basic Syntax

You can now use the command to search for files using this syntax:

The vanilla locate command can sometimes return files that have been deleted, if the database wasn’t updated. The best solution is to manually update the database by running the following:

How to Use Linux Locate Command

We’ll share with you the most common applications of Linux locate command.

Search Exact File Name

The basic syntax only allows you to search for files that contain the search term. If you want to get the file with the exact name, you can use the -r option and add dollar symbol ($) at the end of your search term, for example:

Count the Number of Files

In order to tell how many files appear on your search result, insert -c after the locate command.

Instead of listing all the files, it will give you the total number of them.

Ignore Case Sensitive

Use -i on your linux locate command to ignore case sensitive files. For instance:

All of the files with this name will be shown, regardless of any uppercase or lowercase symbols found.

Show Existing Files

Just like we’ve mentioned, Linux locate command can even show you a deleted file if you haven’t updated the database. Thankfully, you can get around this problem by using -e option, like this:

By doing this, you will only get files that exist at the time you perform the locate command.

Disables Errors While Searching

-q option will prevent any errors from showing up when the search is being processed. To do this, simply enter:

Limit the Number of Search Results

If you want to limit the number of search results, -n will do the trick. However, remember that you need to put the option at the end of the command line. Take a look at this example:

The script will only display the first 10 files it discovers even when there are more.

Conclusion

You can search for files on your server using the find and locate commands in Linux. These two powerful tools have their own advantages. Therefore, we encourage you to give both of them a go and see which one is more suitable for you. Here’s a short summary of what we talked about:

  • Use find to search for files based on name, type, time, size, ownership and permissions, in addition to some other useful options
  • Install and use Linux locate command to perform faster system-wide searches for files. It also allows you to filter out by name, case-sensitive, folder, and so on.

If you have any questions, feel free to ask in the comments!

Domantas leads the content and SEO teams forward with fresh ideas and out of the box approaches. Armed with extensive SEO and marketing knowledge, he aims to spread the word of Hostinger to every corner of the world. During his free time, Domantas likes to hone his web development skills and travel to exotic places.

Источник

Читайте также:  Джойстик speedlink windows 10
Оцените статью