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 name. 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. Switching between operating systems and shutting down the machine at the end of the day prevents cron from automatically updating the database.

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.

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.

The find command is one of the most useful and important commands on Linux.
It is installed by default and available on almost all versions of Linux. In Linux, everything is stored as files, and it's obviously worth knowing how to look for these files.

Using the find command, you can search for files of interest using a number of search criteria. The criteria can be specified both together and separately, and then actions can be taken with the result obtained. In this tutorial, we are going to describe the find command with usage examples.

1) List all files in the current directory and its subdirectories

To list all the files in the current directory and its subdirectories, we can use:

Alternatively, we can also use 'find. ’ which will give you the same result.

2) Find all files and directories in your current working directory

If you only need to find directories, you can use:

$find. -type d

To find only files and not directories:

$find. -type f

3) List all files in a specific directory

In order to find files from a specific directory you need to enter:

$ find /root

This command will look for all the files in /root directory.

4) Find the file by name in the directory

To search for a file by name in a specific directory, enter:

$ find /root -name "linuxtechi.txt"

This command will look for the linuxtechi.txt file in the /root directory. We can also find all files with the extension .txt:

$ find /root -name "*.txt"

5)Find the file in multiple directories

To search for files in multiple directories, enter:

$ find /root /etc -name "linuxtechi.txt"

With this command, we can look for linuxtechi.txt file in /root & /etc directories.

With this command we can find the linuxtechi.txt file in the /root and /etc directories.

6)Find the file by name, case insensitive

Search for case-insensitive files using -iname:

$ find /root -iname "Linuxtechi.txt"

As a result, you will get all files called linuxtechi.txt. In this case, there may be several files, since linuxtechi.txt will be equal to LINUXTECHI.txt.

7) Find all file types other than those mentioned

Let's assume that we need to find all files other than a certain file type. To achieve this we enter:

$ find /root -not -name "*.txt"

8)Find files based on multiple criteria

We can combine more than one condition when searching for files. Let's assume that we need files with .txt and .html extensions:

$find. -regex ".*\.\(txt\|html\)$"

9)Find files using OR condition

We can also combine several search criteria, which will lead to a search for files based on satisfying one of the conditions. This is done using the OR operator:

$ find -name "*.txt" -o -name "linuxtechi*"

10)Search files based on permissions

To find files with specific access use -perm:

$ find /root -type f -perm 0777

11)Find all hidden files

To search for hidden files in a directory, enter:

$ find ~ -type f name ".*"

12) Find all files with SGID

To search for files with SGID bits, run the command:

$find. -perm /g=s

13) Find all files with SUID

To search for files with SUID bits we use:

$find. -perm /u=s

14) Find all executable files

To search only executable files, enter:

$find. -perm /a=x

15) Find read-only files

In addition, you can use the find command to find read-only files:

$ find /root -perm /u=r

16)Find all user files

To search for files of a specific user, use the following command:

$find. -user linuxtechi

17)Find all group files

To search for files of a specific group, use:

$find. -group apache

18) Find all files of a certain size

If we want to search whose size we know, then we can use -size:

$ find / -size -2M

19)Find all files in a size range

If we are looking for a file whose size we do not know, but we know its approximate size, or we simply need to make a selection of files in a certain size range, then we can enter:

$ find / -size +2M -size -5M

You can use the find command when searching for files larger than, for example, 50 mb:

$ find / -size +50M

20) Find files modified N days ago

For example, we want to locate all the files that have been modified 8 days ago. We can accomplish that using ‘-mtime‘ option in find command

For example, we can find all files edited 8 days ago. This is done using the -mtime command:

$ find / -mtime 8

21)Find files that were accessed N days ago

You can find files that were included 8 days ago using -atime:

$ find / -atime 8

22) Find all empty files and directories

To find all empty files in the system, enter:

$ find / -type f -empty

And to display their directories:

$ find ~/ -type d -empty

23)Find the largest and smallest files

To display a list of the largest or smallest files, we use find in conjunction with sort , and if we need to display the 3 “most-most”, then we also use head .

To output three files from the current directory, enter:

$find. -type f -exec ls -s () \; | sort -n -r | head -3

In a similar way, we can display the smallest files in the current directory:

$find. -type f -exec ls -s () \; | sort -n | head -3

24) Find all files with a certain access and change it to 644 (or something else)

The find command can offer advanced use cases. For example, we can change all permissions of 644 specific files to 777. To do this, we execute:

$ find / -type f -perm 644 -print -exec chmod 777 () \;

25)Find all files that match certain criteria and delete them

Sooner or later you may need to delete certain files. If this happens, then enter:

$ find / -type f -name "linuxtechi.*" -exec rm -f () \;

The above examples perfectly demonstrate the capabilities of the find command, which can greatly simplify the task of finding files.

When starting to work with a Linux server, users often encounter the problem of finding the necessary files.

This tutorial covers the use of the corresponding find command, which allows you to search for files using various filters and parameters. Additionally, this guide briefly covers the locate command, which can be used to locate commands.

Search by file name

Of course, searching for a file by name is the most obvious way to find the file you need.

To do this use:

find -name "query"

This command is case sensitive (that is, it treats files named file and File as two different files).

To find a file by name, insensitive to case, type:

find -iname "query"

To find files that do not match a particular pattern, you need to invert the search using the -not flags or the "!" metacharacter. Please note that when using "!" you need to escape characters so that the bash shell doesn't interpret the "!" even before the find command is executed.

find -not -name "query_to_avoid"

find\! -name "query_to_avoid"

Search by file type

Using the "-type" parameter, you can specify the type of the required file. It works like this:

find -type type_descriptor query

Here is a list of common descriptors that can be used to indicate the file type:

  • f: regular file;
  • d: directory;
  • l: symbolic link;
  • c: character devices;
  • b: block devices.

For example, to find all character devices in the system, you need to run the command:

find / -type c
/dev/parport0
/dev/snd/seq
/dev/snd/timer
/dev/autofs
/dev/cpu/microcode
/dev/vcsa7
/dev/vcs7
/dev/vcsa6
/dev/vcs6
/dev/vcsa5
/dev/vcs5
/dev/vcsa4
. . .

To find all files that end in .conf use:

find / -type f -name "*.conf"
/var/lib/ucf/cache/:etc:rsyslog.d:50-default.conf
/usr/share/base-files/nsswitch.conf
/usr/share/initramfs-tools/event-driven/upstart-jobs/mountall.conf
/usr/share/rsyslog/50-default.conf
/usr/share/adduser/adduser.conf
/usr/share/davfs2/davfs2.conf
/usr/share/debconf/debconf.conf
/usr/share/doc/apt-utils/examples/apt-ftparchive.conf
. . .

Filter by time and size

The find command allows you to filter the result based on size and last modified time.

file size

To filter files by size, use the -size parameter.

You also need to add a suffix at the end of the value to indicate the size:

  • c: byte
  • k: kilobyte
  • M: megabyte
  • G: gigabyte
  • b: blocks of 512 bytes

To find files exactly 50 bytes in size, type:

find / -size 50c

To find files that are smaller than 50 bytes, use the "-" symbol in front of the value:

find / -size -50c

Accordingly, to find files larger than 700 megabytes, use the + symbol in front of the value; the command looks like this:

find / -size +700M

Search based on time

Linux stores data about access time, modification time and change time.

  • access time: time of the last access to the file (when the file was read or appended);
  • modification time: time of the last modification of the file contents;
  • change time: time of the last change of the inode of the file.

To filter files by time, use the "-atime", "-mtime" and "-ctime" parameters respectively.

The value of this parameter indicates how many days ago the file was modified. As with file size, you can use the – and + symbols to get files modified less than or more than n days ago.

That is, to find a file whose contents were modified 1 day ago, use:

To list files that were accessed less than 1 day ago, use:

find / -atime -1

To find files whose inodes were changed more than three days ago, enter:

find / -ctime +3

There are also related options that let you specify minutes instead of days:

This will return files whose contents were changed a minute ago.

Additionally, the find command can compare files and output the newer ones:

find / -newer myfile

Search by owner and privileges

Using the find command, you can search for files by owner or file permissions.

For this, the parameters –user, –group, and -perm are used, respectively. For example, to find a file owned by a user named syslog, type:

find / -user syslog

Likewise, to list files belonging to the shadow group, use:

find / -group shadow

You can also search for files with special privileges.

To find a file with specific permissions, use:

find / -perm 644

This line will display all files with these rights.

To list all files whose privileges are greater than or equal to the specified ones, use the syntax:

find / -perm -644

This will return all files with additional privileges (for example, a file with privileges 744).

Filtering files by depth

To run the examples in this section, create a directory structure in the temporary directory. It should consist of three levels of directories, with ten directories on the first level. Each directory (including the test directory) must contain ten files and ten subdirectories.

To create such a structure, run the following command:

CD
mkdir -p ~/test/level1dir(1..10)/level2dir(1..10)/level3dir(1..10)
touch ~/test/(file(1..10),level1dir(1..10)/(file(1..10),level2dir(1..10)/(file(1..10),level3dir( 1..10)/file(1..10))))
cd ~/test

To review the structure you just created and check that everything was created correctly, use the ls and cd commands. Then return to the test directory test:

This section will show you how to extract specific directories from this structure. To get started, try a simple search for the file by name:

find -name file1







./level1dir7/level2dir8/level3dir6/file1
./level1dir7/level2dir8/level3dir5/file1

. . .

This command produced a fairly voluminous result. By passing this result to the counter, you can see that in the end 1111 files were output.

find -name file1 | wc -l
1111

Of course, in most cases this conclusion is too lengthy and inconvenient. Try narrowing it down.

To do this, you can use the –maxdepth parameter to set the maximum search depth:

find -maxdepth num -name query

To find file1 in level1 and higher directories, specify a maximum depth of 2 (1 for the top-level directory and 1 for level1 directories).

find -maxdepth 2 -name file1
./level1dir7/file1
./level1dir1/file1
./level1dir3/file1
./level1dir8/file1
./level1dir6/file1
./file1
./level1dir2/file1
./level1dir9/file1
./level1dir4/file1
./level1dir5/file1
./level1dir10/file1

As you can see, this result has a much more convenient appearance.

In addition, you can specify the minimum search depth:

find -mindepth num -name query

This is used to find files that are at the end of directory branches:

find -mindepth 4 -name file
./level1dir7/level2dir8/level3dir9/file1
./level1dir7/level2dir8/level3dir3/file1
./level1dir7/level2dir8/level3dir4/file1
./level1dir7/level2dir8/level3dir1/file1
./level1dir7/level2dir8/level3dir8/file1
./level1dir7/level2dir8/level3dir7/file1
./level1dir7/level2dir8/level3dir2/file1
. . .

Again, this result will contain a huge number of files (1000).

The maximum and minimum search depths can be combined to reduce the search range:

find -mindepth 2 -maxdepth 3 -name file
./level1dir7/level2dir8/file1
./level1dir7/level2dir5/file1
./level1dir7/level2dir7/file1
./level1dir7/level2dir2/file1
./level1dir7/level2dir10/file1
./level1dir7/level2dir6/file1
./level1dir7/level2dir3/file1
./level1dir7/level2dir4/file1
./level1dir7/file1
. . .

Executing and Combining Commands

The find utility allows you to execute any auxiliary command on all found files; The –exec option is used for this. The basic syntax looks like this:

find search_parameters -exec command_and_parameters () \;

The () characters are used as placeholders for found files. Symbols \; are used to allow find to determine where the command ends.

For example, you can find files with privileges 644 (as in the previous section) and change their privileges to 664:

cd ~/test
find . -perm 644 -exec chmod 664 ()\;

Then you can change the directory privileges:

find . -perm 755 -exec chmod 700 ()\;

To chain multiple results, use the -and or -or commands. The –and command is assumed if omitted.

find . -name file1 -or -name file9

Finding Files Using the Locate Command

The locate command is an alternative to find. This command is generally faster and can easily search the entire file system.

You can install this command using apt-get:

sudo apt-get update
sudo apt-get install mlocate

But why is the locate command faster than find? The thing is that locate depends on the database of files on the filesystem.

Typically, the cron script updates this database once a day; but it can also be updated manually. Run this command:

Remember: the database must be updated regularly so that it contains current data; otherwise, it will be impossible to find recently received or created files.

To find files using the locate command, simply use the following syntax:

The result can also be filtered.

For example, to return only files that contain the request itself, rather than listing every file that contains the request in the directories leading to it, you can use the -b flag (to search only basename, the base name of the file):

To have the locate command return only files that still exist on the file system (that is, files that were not deleted between the last time you ran updated and the current call to locate), use the -e flag:

To view the statistics cataloged by the locate command, use the –S option:

locate -S
Database /var/lib/mlocate/mlocate.db:
3,315 directories
37,228 files
1,504,439 bytes in file names
594,851 bytes used to store database

Results

The find and locate commands are excellent tools for locating files on UNIX-like operating systems. Each of these utilities has its own advantages.

Although the find and locate commands are very powerful on their own, they can be enhanced by combining them with other commands. Once you've learned how to use find and locate, try filtering their results using the wc, sort, and grep commands.

Tags: ,

    Find the file by its name. This simplest search is performed using the find utility. The below command will search for a file in the current directory and all its subdirectories.

    find -iname "filename"

    • Type -iname instead of -name to ignore case in the entered file name. The -name command is case sensitive.
  1. Start searching in the root directory. To run a system-wide search, add the / modifier to the query. In this case, the find command will search for the file in all directories, starting with the root one.

    find / -iname "filename"

    • You can start searching in a specific directory; to do this, replace / with the directory path, for example /home/max .
    • Can be used. instead of / to search for the file only in the current directory and its subdirectories.
  2. Use the wildcard symbol.* to find files whose name matches part of the request. Using the wildcard character *, you can find a file whose full name is unknown, or find all files with a specific extension.

    find /home/max -iname "*.conf"

    • This command will find all files with a .conf extension in the user's Max folder (and its subfolders).
    • Use this command to find all files whose names match part of the query. For example, if you have a lot of WikiHow-related files on your computer, find all the files by typing "*wiki*" .
  3. Make it easier to manage your search results. If there are too many search results, it will be difficult to find the file you need among them. Use the | so that search results are filtered by the less command. This will make it easier to browse and filter your search results.

    find /home/max -iname "*.conf" | less

    Find specific elements. Use modifiers to show only certain items in search results. You can search for regular files (f), directories (d), symbolic links (l), character-based I/O devices (c), and block devices (b).

    find / -type f -iname "filename"

  4. Filter your search results by file size. If you have many files with similar names on your computer, but you know the size of the file you're looking for, filter your search results by file size.

    find / -size +50M -iname "filename"

    • This command will find all files larger than 50 MB. Use the + or - modifier to indicate an increase or decrease in size. If there is no + or - modifier, the command will find files whose size exactly matches the specified size.
    • You can filter your search results by bytes (c), kilobytes (k), megabytes (M), gigabytes (G), or 512-byte blocks (b). Please note that the modifiers shown are case sensitive.
  5. Use logical operators (Boolean operators) to combine search filters. You can use the -and , -or , -not operators to combine different search queries into a single query.

    find /travelphotos -type f -size +200k -not -iname "*2015*"

    • This command will find files in the Travelphotos folder that are larger than 200 kB and do not have the number 2015 in their names.