Open
Close

Using Find and Locate to find files on a Linux server. How to search for files in Linux using the find command How to find a file in ubuntu by name

There may be times when you know a file or directory exists, but you don't know how to find it. There are several commands that will help you with this: find , locate and which .

4.10.1. find command

The find command has the following format:

Find path sample_for_search

If you do not specify a path, find will begin searching for the specified pattern in the current directory and continue through all subdirectories therein.

The find command has many options, which can be found by reading the man page (type man find at the command prompt). The most commonly used option is -name, which specifies a search for all files and directories containing a specific combination of letters in the name.

Find. -name tes

This command searches the current directory for all files containing “tes” in the name.

4.10.2. locate command

With this command you can see all files or directories whose names contain the pattern you are looking for. For example, to search for a file containing the word dog in the name, enter at the command line:

Locate dog

The locate command uses a database to locate files or directories that contain the word dog in their names. Search results might include a file called dog, a file called bulldog.txt, a directory called /dogs/, and so on. To learn more about the locate command, see its man page (type man locate at the command prompt).

Provided the database is up to date, the locate command performs searches very quickly. The locate command's database is updated every night using the cron service.

cron is a small program that runs in the background and performs various tasks (such as updating the locate command database) at regular intervals. To access the cron manual, type man cron at the command prompt.

cron periodically updates the slocate database, which is used to locate files or directories.

To update the database manually, log in as root (by typing su - at the command prompt and entering root's password) and type updatedb at the command prompt.

After some time, the slocate database used by the locate command will be updated.

When you have finished the work that requires you to be root, type exit on the command line - you will return to your session.

find command in Linux/FreeBSD. Find command syntax.

Find command syntax:

# find [path] [options] [search parameters] [actions on files]

Path- where to look for files, you can use a list of paths separated by spaces.

Options- starting with the symbol “-”, followed by the name of the option:
-d Search subdirectories before searching the directory itself
-L When searching, follow symbolic links
-maxdepth N When searching, check no more than N nested directory levels
-mindepth N Do not scan subdirectories of level N or less
-mount Do not search in directories of other file systems

Search options

-atime N The file was last accessed N days ago
-mtime N The file was last modified N days ago
-name Pattern File name (name pattern) without specifying the path. It is recommended to always enclose the pattern in quotation marks
-size [±]N The file size is N blocks, if +N is specified, then the file size is greater than N, -N is less. The character after N indicates the block size. b - 512 bytes, c - byte, w - 2 bytes, k - kilobyte, M - megabyte, G - gigabyte.
-type N File type N. The most commonly used values ​​for N are: d - directory, f - file.
-user Username The file is owned by a user named Username.

Examples of using the find command using parameters:

# find . -type f -name "~*" -print

Find regular files (not directories) in the current directory whose names begin with the "~" character.

# find . -newer file.bak -type f -print

Find files in the current directory that have been modified more recently than file.bak.

Operators
Criteria can be combined using operators. The following are the operators in descending order of precedence.

Short form Long form Description
!criteria -not Negation (returns true if the criterion is false)
criterion1-a criterion2 -and AND operator (true if criterion1 and criterion2 are true)
criterion1-o criterion2 -or OR operator (true if criterion1 or criterion2 is true)

In general, when using operators, criteria are checked in order of priority. You can change the order using parentheses. Parentheses must be separated using a backslash.

Examples of using the find command using operators

#find. \(-name "%*" -or -name "temp*" \) -type f -print

Find files in the current directory that begin with the symbol "%" or with "temp" and are files ( -type f), rather than directories.

# find . -maxdepth 1 \(\(-size +600M -and -size -1G \) -or -name "*.mpeg" \) -and -type f

Find in the current directory (without processing subdirectories - -maxdeph 1) regular files ( -file f) larger than 600MB and less than 1GB (-size) or files whose name ends with “.mpeg” (-name).

Actions on files
When the find command is executed, you can perform various actions on the files found. Let's look at the main ones.

Exec command\; - Execute the command. Please note that the command is followed by a backslash and a semicolon.
-execdir command\; - Same as exec, but the command is called from the subdirectory containing the current file.
-ok command \; - The same as exec, but before processing the next file, a request to execute the command will be displayed.
-okdir command \; -Same as ok for execdir.
-print - Print the file name to the screen.
-ls - Execute the ls -dils command on the current file.

In executable commands you can use parameter () as an argument, which is replaced by the path to the current file.

Examples of using the find command using actions

# find . -size +1000c -type f -ls

Find regular files larger than 1000 bytes in the current directory and run the ls -dils command on them (ls action).

# find . -name "~*" -type f -ok rm () \;

Find regular files in the current directory starting with the tilde character “~”, and for each file issue a request to delete it (to execute the rm command).

EXAMPLES:

Search files by their size

# find /var/log -name "*.log" -and \(-size +1k -and -size -1000k \) -and -type f -print

Files with the *.log extension, ranging in size from 1kb to 1000kb, will be found and displayed.

Search files by their owner and group

This command will find all files that do not have an owner

Options -user or -uid allow you to search for files by user ID (UID) and username, and the option -group by group name.

# find . -name "*.log" -user root -group root

Finds all files in the current directory with the extension log of the root user and root group

# find -user root -o -user www

Finds all files of root or www user

Using Regular Expressions

Utility find supports regular expressions. Let's give an example right away. Let's say I want to find all files whose extensions are .php or .js. I could do it like this:

# find -regextype posix-egrep -regex ".*(php|js)$"

It looks a little complicated, doesn't it? As a refutation, we point out that the syntax used here is egrep (-regextype posix-egrep), and then specifies the regular expression used for the search. The expression begins and ends with single quotes to prevent the shell itself from trying to process the regular expression. Then comes the expression.*, which uses a wildcard that matches any character or set of characters. The (php|js) part says to search for php or js. The pipe (|) in this expression matches the Boolean "or" expression. Finally, the dollar sign ($) that ends the expression indicates that we are looking for these extensions at the end of the file name. So if you have a file named js.txt, it won't match the search criteria.

Working with time
The find utility has everything you need to search by the time a file was worked on. You can search by access time ( -atime), either by the time of the last modification of the file (-mtime), or by the time of its last change ( -ctime).

For example, let's find all files that have not been modified in the last two days:

# find -mtime +2

If you want to search for files within a specific range, you can combine the options. So the command find -mtime +2 -mtime -5 would mean "two or more days ago, but not more than five days ago."

We work with minutes
Sometimes you need to search for files that have been modified within the past day, and the previous search options are not very accurate for this. The good thing about find is that it also has parameters. -amin, -cmin And -mmin, which are similar to the previously discussed options, but they use minutes rather than days. So if you want to look at which files have been modified or accessed in the last day, you can use these options.

Search restrictions
Sometimes the find utility provides more results than you need. You can limit the search results returned by find by specifying the parameter maxdepth. For example, if you want to find all the JavaScript files in the WordPress directory, you can use the following command:

# find wordpress -name "*js"

But what if you only want to see the JavaScript files that are in the top-level directory? You can limit your search using the parameter -maxdepth:

# find wordpress -maxdepth 1 -name "*js"

The search will only be carried out in the WordPress directory, and not in subdirectories. If you change the value -maxdepth by 2, then the search will be carried out in subdirectories of the WordPress directory, but not in deeper subdirectories.

Combining the find utility with other commands
Now that you've found the files you were looking for, what are you going to do with them? You can use the parameters in the find utility xargs or -exec, which allow you to specify the action to take on files after you find them.

Let's say you want to change the owner of a file from root to www-data for a large number of files at once. Finding all these files is only the first step, you also need to change the owner of the file. Do this manually using the list returned by the utility find, quite tiring. Therefore, to change file owners you may want to use the option -exec:

# find -user root -exec chown www-data()\;

The need to search for files can arise in almost every operating system that allows you to work with a file system. A classic example for us will be the Linux operating system, which we will use in console mode. Let's look at the possibilities of searching for files in the system using the console. To search for files in the Linux system, there is a find command, which allows you to perform a fairly flexible search, allowing you to specify additional search criteria. Let's take a closer look at the capabilities of this command.

Find command syntax:

Find path –options

The path is the directory in which to search. For example, these could be values ​​like this:
. – current directory
/ - root directory
~ - home directory

After specifying the path, search options are indicated. Everything looks confusing, but in reality there are no difficulties here.

Main options:
-name- search by name, set the search pattern;
-user- search for files belonging to a specific user;
-group- search for files belonging to a specific group;
-perm- search for files by access mode;
-type- search for files by type, list of types:

  • b- special block file;
  • d- catalogue;
  • c- special symbol file;
  • f- regular file;
  • l- symbolic link;
  • p- named pipe;
  • s- socket.

-size n- search for files with size n units;
-mtime -n +n- search for files by modification date, less (-) or more (+) days ago.

Let's try to search for files, simulating various situations.
Let's find the files on a removable device connected to USB and pre-mounted in the system.

Search files by extension:

$ find /mnt/usb -name "*.mp3" -print

As a result of executing this command, a search will be performed in the directory /mnt/usb– this is the directory in which the device is mounted. The search will be performed on all files (*) with the extension .mp3.
The search mask can be changed quite flexibly; for example, you can set a keyword with which the file name begins and search for it.

Search files by starting keyword:

$ find ~ -name "config*" –print

The result will show a list of found files starting with the keyword config.
One of the strengths of the command is the ability to search according to a regular expression. For demonstration, we will search for files starting with Latin letters from “a” to “j”.

Search files using a regular expression pattern:

$ find / -name "*" –print

According to the specified pattern, a search will be made for all files in the system starting with the letters “a” to “j”.

Anyone more or less familiar with Linux systems knows that file access modes are a very important matter. Sometimes you need to find files that have specific specified rights; for these purposes, you can use the search with the option –perm.

Search for files with access mode 755:

$find. -perm 775 –print

In the same way, you can make a more flexible search. Let's find files by user group that have full access.

Search for files with permissions for a group:

$find. -perm -070 –print

The hyphen sign can be replaced with a plus sign, this will allow you to search for files that have at least one of the specified permission bits set, the remaining bits will be ignored.

In the following example, consider searching for files belonging to a specific user or group.

Search for files of a specific user:

$ find / -user admin –print

As a result of the search, files belonging to the user will be found admin.

Search for files belonging to a specific user group:

$ find / -group bots –print

Files that belong to the user group will be found bots. In addition, you can search for files whose owners are non-existent users or groups:

$ find / -nouser –print $ find / -nogroup –print

The ability to search for specific file types is also an important functionality. For example, if there is a need to find all symbolic links in a specific directory.

Search for symbolic links:

$ find /etc -type l –print

The search will be performed in the /etc directory, in which all symbolic links will be selected.

It may be necessary to view a list of subdirectories in a particular directory; for such tasks there is the following command.

View subdirectories in a directory:

$ find /mnt/usb -type d –print

The screen will show a list of directories present in the directory /mnt/usb. Now let's move on to the next option, this is the ability to search for files of a set size.

Search files by size:

$find. -size 2000k –print

A search will be made for files with a size of 2000 kilobytes; the sizes can also be specified in megabytes; for this, instead of the letter “k”, you should specify the letter “M”.

As the next example, we will use the ability to search files by their modification time. For these purposes we will use the option –mtime.

Search for files modified in the last 2 days:

$ find /var/www/html -mtime +2 –print

The search will be performed in the directory /var/www/html, and will search for files that have changed during the last 2 days. Perhaps one of the most important and convenient search options. You can also search by modification date with the opposite condition. Let's try to find files in the directory that have not changed for 5 days.

Search for files that have not changed for 5 days:

$ find /var/www/html -5 –print

That's all for now, I hope these examples helped you understand this command. Its convenience is presented clearly, and it will not be superfluous to know about its capabilities, especially if you are going to work with the Linux system in the future. The skills of competent file search significantly save your personal time, and as you know, time is priceless. Good luck in your work!

If you often work at the command line on a computer or server that does not have a graphical shell at all, sooner or later you will be faced with the task of searching for files. Fortunately, Linux already has a built-in command that allows you to find a file on the system.

Today we will talk about using the find command - believe me, it is worth learning how to work with this powerful and convenient tool.

How to use the find command

To put it simply, the basic syntax of the find command is as follows:

Find /path parameters filename

Let's understand the capabilities of the team

Search for a file by name

The first parameter is the path. If you have no idea where the file might be hiding, replace the path with / - that's enough. However, searching the entire disk can be quite time-consuming, and if you know where the file may be located, specify the folder to start searching from (for example, ~ to search in the user's home folder).

Now let's move on to the search parameters. There are two options for searching a file by name:

  • name - search for case sensitive file name
  • iname - search case-insensitive file name

It must be remembered that in Linux the case of the file name is important, and if you need to find, for example, the file Ubuntu.txt, then the following command will not give any results:

Find / -name ubuntu.txt

But you can use the iname command and perform a case-insensitive search:

Find / -iname ubuntu.txt

Search by type

The find command allows you to search for more than just files. Here are the types of handles search supports:

  • f - regular file
  • d - directory
  • l - symbolic link
  • c - character device
  • b - block device

For example, to find all directories within the current user's home directory that begin with "config", run the following command:

Find ~ -type d -name config*

Outputting search results to a file

The convenient function of outputting the result of a command to a file will be extremely useful if there are a lot of search results or there is a need to work with them later. For example, in order to save a list of all found configuration files to a file conf_search, run the following command:

Find /etc -type f -name “*.conf” > conf_search

Search files by size

This is a very useful option when you are running out of disk space and need to figure out where it went. For example, to find files larger than 1000 MB, run the following command:

Find / -size +1000M

The following size abbreviations can be used:

  • c - bytes
  • k - kilobytes
  • M - megabytes
  • G - gigabytes
  • b - blocks of 512 bytes

These are just a few ways to use a powerful command. More ways can be found in the manual by running the command

Hello to the entire Habr community.
This is my first post and hopefully not the last. Therefore, all sorts of shortcomings, bugs and some wateriness of the text are inevitable, so please do not judge strictly :)
I was prompted to write this post by the topic “Console for a beginner.” , where ISVir raised, in my opinion, a pressing topic - how to tell newcomers about the console in an accessible language, without scaring them off with its imaginary super-complexity.

I’m not going to take away parity from ISVir, I’ll just tell you about the practical use of several of the most basic “every day” utilities, without which working in the console is impossible for me.

So what we have:

find- search for files. allows you to search for files, directories, symlinks and other file objects. find Allows you to specify many search options such as:

  • search by mask (in name)
  • control of search nesting depth
  • search for specific file types (directory, symlinks, sockets)
  • search by file creation/modification time
  • you can set the size (from and to in range) of the file
  • perform actions on each found file
In the find mana you can read about other options and parameters.

So, right off the bat - search for all files in the /etc/ directory that have been changed in the last 24 hours:

$find /etc/ -type f -mtime -1

Let's look at what we wrote:

The first parameter is always the starting directory to search.
option -type with parameter f speaks find, that you need to search only for ordinary files.
option -mtime with parameter -1 indicates find that you need to find files that have changed in the last 24 hours.
"-" before 1 sets the upper limit of the range, i.e. “everything that has changed in the last 24 hours”

If we indicated "+" before 1 , That find would find all files that changed from 01/01/1970 to yesterday (more than a day ago)
You can also specify the exact date by putting a number without a modifier.

Perform actions on found files.
option -exec accepts a line with a command that will be executed for each found file
the parameter passed to the command is indicated by {}
the line must end with the characters " \; "

Let's look at an example:
* find in the /tmp directory all files that have changed over the last month and copy them to the directory
/tmp/backup/

$find /tmp -type f -mtime -30 -exec cp () /tmp/backup \;

* delete all directories (recursively) with the name logs that have changed in the last day in the directory
/var/www
$find /var/www -type d -mtime 0 -name logs -exec sudo rm -fr () \;

parameter d in option -type indicates search only directories
option -name searches by name.
It’s worth adding here that deleting files in this way is not optimal (slow).
To delete, find has a built-in option -delete, which is an order of magnitude faster.

Let's consider the utility awk.
awk is a programming language designed for file processing. Its purpose
development - to facilitate the formulation and solution of many problems related to the processing of text information. In fact, awk is a utility available from the console.
For obvious reasons, I will not consider techniques for writing awk code here - I will only tell you about one technique that is important for us.

First, awk can get data from STDIN: $echo "test"|awk ...
secondly, awk is effective when writing one-liners in the console, because executes the code given to it as a parameter:


awk splits the input stream into fields and places these fields in variables like $1,$2,..$N
By default, the field separator is space, but using the option -F"_delimiter_" this can be overridden:
$head -4 /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh

$cat /etc/passwd|awk -F":" "(print $1)"
root
daemon
bin

For example, we have several sites in the /var/www directory. for each site there is a logs directory, where Apache logs are written (for this site). And now we want to find out the total volume of these logs, as well as find all logs larger than 100Mb.

1.search for large logs:

$find /var/www -type f -name “access.log*” -size +100M
/var/www/site1/logs/access.log
/var/www/site2/logs/access.log.1.gz

2.calculate the total volume of logs:

Find /var/www/ -type f -name "access.log*" -exec du -k () \;|awk "(s+=$1)END(print s)"
5071604


So, don’t be scared - I’ll explain everything right now :)

Find searches for all files by mask (access.log*) and runs the command for each du.
team du prints the file size. option -k outputs in kilobytes.
then the processor starts awk, simply sums the first field of strings (numbers) into a variable s and displays the value of the variable on the screen.

Another example: let’s find all the files and directories in the system that belong to the user test1 and calculate the total volume.

#find / -user test1 -exec du -sm () \;|awk "(s+=$1)END(print s)"

those. here using the option -user find searches for files belonging to user test1 and for each file/directory we calculate its size (du command)
Then awk receives this data through the conveyor and, as we did above, calculates their sum in Kb.

OK. I think that's enough for today.
The post turned out to be quite large, apparently out of habit :)

I want to say right away that my goal was not to simply talk about the use of find and awk, but to give examples of practical application in real situations.
If you like the article, I will continue to write in this direction.

Thank you for your time.