The find command: a powerful way to find files in Linux. How to find a file in Linux How to find a file in Linux

I would like to point out right away that there are many different ways to implement search in Linux. Now, for example, the beagle project is developing very strongly. But I'll talk about standard methods search in Linux and Unix. Namely, I want to describe the use of the findutils suite of programs.

Of the set of programs contained in this package, we will be interested only in find and xargs.
Let's start with find. The find command is a universal search tool; it allows you to search for files and directories, view all directories in the system or only a specified one, search for files of a specified depth and files with specified attributes. Usually users know that there is a find command to search in Linux, but the use of this command ends with two or three known options. For an effective search, it is advisable to explore most of the available options.

Usage:
find [-H] [-L] [-P] [path...] [expression]

-P- never follow symbolic links. This option is enabled by default;
-L- follow symbolic links. In this case, the find command displays information about the file pointed to by the given link.
-H- do not follow symbolic links except when processing arguments command line. Information is taken from the link itself

Default path: current directory; default expression: -print; an expression can consist of operators, options, tests and actions:

operators (in order of decreasing precedence; -and is taken by default if no others are given):
(EXPR)! EXPR -not EXPR EXPR1 -a EXPR2 EXPR1 -and EXPR2
EXPR1 -o EXPR2 EXPR1 -or EXPR2 EXPR1 , EXPR2

position dependent options (always true): -daystart -follow -regextype

usual options:
-depth --help -maxdepth LEVELS -mindepth LEVELS -mount -noleaf
--version -xdev -ignore_readdir_race -noignore_readdir_race

tests:(N can be +N or -N or N): -amin N -anewer FILE -atime N -cmin N
-cnewer FILE -ctime N -empty -false -fstype TYPE -gid N -group NAME
-ilname TEMPLATE -iname TEMPLATE -inum N -ipath TEMPLATE -iregex TEMPLATE
-links N -lname TEMPLATE -mmin N -mtime N -name TEMPLATE -newer FILE
-nouser -nogroup -path PATTERN -perm [+-]MODE -regex PATTERN
-wholename PATTERN -size N -true -type -uid N
-used N -user NAME -xtype

actions:-delete -print0 -printf FORMAT -fprintf FILE FORMAT -print
-fprint0 FILE -fprint FILE -ls -fls FILE -prune -quit
-exec COMMAND; -exec COMMAND() + -ok COMMAND;
-execdir COMMAND; -execdir COMMAND () + -okdir COMMAND;

Let us describe the most used of them:

- name- search for files whose names match a given pattern;
- print— place a record of the full names of the found files in the standard output stream;
-perm— search for files by access mode;
- user— search for files belonging to a given user
-nouser— search for files belonging to a non-existent user, i.e. which is not in /etc/passwd;
-group— similar to -user, only for a group;
-nougroup— similar to -nouser, only for a non-existent group;
- mtime -n (+n)— search for files that were modified less than -n or more than +n days ago;
-atime— search by date of last reading;
-ctime -last modified file attributes;
- type— search for the specified file type. Those. f is a regular file, d is a directory, etc.;
-size n— search for files of size n units; units: c - byte, k - kilobyte, b - block (depending on the system);
- mount— search in the current file system;
-exec— execution of the shell command for the found files.

Examples of using the find command:
$ find /home -user serhiy
Find all files in the /home directory and all subdirectories owned by the user serhiy

$ find ~ -name *.c
Finds all files with the extension .c in your home directory. For example helloworld.c

$find. -name "*"
Finds files starting with a capital letter in the current directory and its subdirectories. Note that the search expression is specified in “...”.
To search for files that you have not modified for a while, use the "-mtime" switch, and for files that have certain time access rights were not changed ago, use “-ctime”. The number after the “+” symbol specifies the number of days (days). To find out which files were modified today, try:
find . -mtime -1 -print
This command will show you which files have been modified in the last 24 hours. Note that to indicate a time "less than" you must include a "-" sign.
$ find /var/www/ -mtime -10
Find files in the /var/www/ directory and its subdirectories that have been modified less than 10 days ago.
$ find /var/www/ -mtime +30 -name "*.php"
Find all .php files in the /var/www/ directory and its subdirectories that have been modified more than 30 days ago.
Let’s find files that have not been read for more than (the “more than” condition is specified by the “+” sign) 30 days:
find . -atime +30 -print
$find. -perm 777
Find all files in the current directory that have permissions 777.

I think by understanding these examples you will be able to easily find the files you need in Linux. The next step is to use find and xargs together.

I already mentioned the -exec option above. With this option, the find command passes all found files to the specified shell interpreter for execution, which are processed once. But there may be difficulties in that the length of the command line may be limited, so if there are too many files, the system will throw an error. The xargs command solves this problem. The fact is that this command processes files received from find not all at once, like -exec, but in portions.
Let's look at some examples of using find with xargs:
$find. -perm 777 | xargs rm
The find command finds files with 777 attributes in the given directory, and the rm command removes them.

Or let's say you want to find the file name.c in your home directory and change its permissions to 777:
$ find ~ -name name.c | xargs chmod 777
And another example of searching in files:
$ grep -ri "???" *,
where ‘???’ is the desired value

If you run this command as an unprivileged user in the system directory, you will probably get a lot of messages like:
$ find: ./backup/pgsql: Permission denied
The following technique will help get rid of them:
$ find ./ -name "milter-spa*" 2>/dev/null
That is, we simply throw out error messages (2 is the STDERR stream descriptor), leaving only the normal STDOUT output.
You can also delete files that match the search criteria or even apply any arbitrary command to them. This is the power of the find utility.
$ find test -nouser -delete
With this command, we will, in one fell swoop, delete all files in the test directory that do not have an owner (i.e., whose UIDs do not appear in the account database). It is clear that in this way you can delete everything found using the -name criterion or any other. Be careful!
$ find ./ -name "*.py" -exec cat () \;
And this way you can display the contents of all Python scripts (more precisely, files with the .py extension). Pay attention to the incomprehensible construction “()” - during execution it will be replaced by the search result, i.e. cat will receive a list of matching files as parameters. The semicolon at the end is also required - this is an indication to find that the exec option has ended. To ";" was not interpreted by the shell, do not forget to escape it.
If necessary, you can always use a rich set of options to search for files based on their time attributes (modification time, access, etc.).
$ find ./ -atime +90d -size +20 -exec tar cjf old.tbz2 () \;
With this terrible design, we will pack into an archive all files larger than 10 kilobytes (20 blocks of 512 bytes; in the GNU version of the utility you can specify the size directly in kilo/mega/gigabytes), which no one has accessed for more than three months.
Search criteria can be very diverse - by file type (directory, symbolic link, regular file, etc.), by owner and group (options -user and -group), by flags and access rights set on the file (-flags and -perm accordingly). To search without taking into account the case of characters, use -iname; in more complex cases, the -regex option is at your service. You can even take into account the type file system(for example, when performing some action, do not take into account files accessible via NFS).
The find utility has a developed language for composing expressions, where different search criteria can be grouped using logical operations (I’ll leave the parsing as an exercise):
$ find ./ -iname "qwe*" -and -size +20 -or -name "Qwert"
The capabilities of find shown above are not exhaustive - these are just a few possible examples. Take the time to read the help (man find), especially paying attention to the examples given there. And life in the console will immediately become easier, life will become more fun.

This article is an excerpt from the book " Linux&Unix - programming in Shell", David Tansley.

I made the edits a little in a hurry; if you notice any typos, please write in the comments.

Often during work there is a need to search for files with certain characteristics, such as access rights, size, type, etc. The find command is a universal search tool: it allows you to search for files and directories, view all directories on the system, or only the current directory.

This chapter covers the following topics related to using the find command:

find command options;

Examples of using various options of the find command;

Examples of using xargs and find commands together.

The capabilities of the find command are extensive, and the list of offered options is also large. This chapter describes the most important of them. The find command can even search disks NFS (Network File System - network file system), of course, if you have the appropriate permissions. In such cases, the command usually runs in the background because browsing the directory tree is time consuming. The general format of the find command is:

find pathname -options

Where path_name- this is the directory from which to start the search. The '.' character is used to denote the current directory, the / character is the root directory, and the "~" character is the one stored in the variable. $HOME the current user's home directory.

2.1. find command options

Let's dwell on the description of the main options of the find command.

Name Searches for files whose names match a given pattern

Print Writes the full names of found files to standard output

Perm Search for files for which the specified access mode is set

Prune This is used to prevent the find command from performing a recursive search on a pathname that has already been found; if the -depth option is specified, the -prune option is ignored

User Search for files owned by a specified user

Group Search for files that belong to a given group

Mtime -n +n Search for files whose contents have been modified less than (-) or more than (+) n days ago; There are also options -atime and -ctime, which allow you to search for files according to the date of last read and the date of last change of file attributes

Nogroup Search for files belonging to a non-existent group for which, in other words, there is no entry in the file /etc/groups

Nouser Finds files owned by a non-existent user, for which, in other words, there is no entry in the file /etc/passwd

Newer file Search for files that are created later than the specified file

Type Search for files of a specific type, namely: b- special block file; d- catalogue; With- special symbol file; p- named pipe; l- symbolic link; s- socket; f- regular file

Size n Search for files whose size is n units; The following units of measurement are possible: b- block size 512 bytes (default setting); With- byte; k- kilobyte (1024 bytes); w- two-byte word

Depth When searching for files, the contents of the current directory are first looked at and only then the entry corresponding to the directory itself is checked

F stype Searches for files that are in a file system of a specific type; Usually the relevant information is stored in a file /etc/fstab, which contains data about the file systems used on the local computer

Mount Searches for files only in the current file system; The equivalent of this option is the -xdev -exec option Execute an interpreter command shell for all detected files; executed commands have the format command ( ) ;

(note the space between the characters () and 😉

Ok Similar to -exec, but displays a prompt before executing the command

2.1.1. Option -name

When working with the find command, the -name option is most often used. It must be followed by a file name pattern in quotes.
If you need to find all files with the extension . txt in your home directory, specify the symbol as the pathname. The name of the starting directory will be extracted from the variable $HOME.

$ find ~ -name "*.txt" -print

To find all files with the extension .txt located in the current directory, use the following command:

$find. -name "*.txt" -print

To find all files in the current directory that have at least one uppercase character in their names, enter the following command:

$find. -name "*" -print

Find in the catalog /etc files whose names begin with the characters " host", the command allows

$ find /etc -name "hoat*" -print

Search the starting directory for all files with the extension .txt as well as files whose names begin with a dot, the command produces

$ find ~ -name "*.txt" -print -o -name ".*" -print

Option -O is a designation for the logical OR operation. If it is used, in addition to files with regular names, files whose names begin with a dot will be found.

If you want to list all files on the system that do not have an extension, run the command below, but be careful as it can significantly slow down the system:

$ find / -name "*" -print

The following shows how to find all files whose names start with lowercase characters, followed by two numbers and an extension .txt(For example, akh37.xt):

$find. -name » [a-x] [a-x] . txt" -print

2.1.2. Option -perm

The -perm option allows you to find files with a specified access mode. For example, to search for files with access mode 755 (any user can view and execute them, but only the owner has the right to write) you should use the following command:

$find. -perm 755 -print

If you insert a hyphen before the mode value, it will search for files for which all of the specified permission bits are set, and the remaining bits will be ignored. For example, the following command searches for files that other users have access to full access:

$find. -perm -007 -print

If a plus sign is entered before the mode value, files are searched for which at least one of the specified permission bits is set, and the remaining bits are ignored.

2.1.3. Option -prune

When you don't want to search a particular directory, use the -prune option. This instructs you to stop searching at the current pathname. If the pathname points to a directory, the find command will not go into it. If the -depth option is present, the -prune option is ignored.

The following command searches the current directory without going into a subdirectory /bin:

$find. -name "bin" -prune -o -print

2.1.4. Options -user and --nouser

To find files owned by a specific user, specify the -user option in the find command, followed by the username. For example, searching the initial directory for files owned by the user dave, is carried out using the following command:

$ find ~ -user dave -print

Search the catalog /etc files owned by the user uucp, executes the following command:

$ find /etc -uaer uucp -print

Thanks to the -nouser option, it is possible to search for files belonging to non-existent users. When using it, a search is made for files whose owners do not have an entry in the file /etc/passwd. There is no need to specify a specific username; the find command does all the necessary work itself. To find all files that are owned by non-existent users and are located in a directory /home, enter this command:

$ find /home -nouaer -print

2.1.5. Options -group and -nogroup

The -group and -nogroup options are similar to the -user-nouser/apps of all files owned by users in the group accts:

$ find /arra -group accta -print

The following command searches the entire system for files belonging to non-existent groups:

$ find / -nogroup -print

2.1.6. Option -mtime

The -mtime option should be used when searching for files that were accessed X days ago. If the option argument is supplied with a '-' sign, files that have not been accessed for a while will be selected. X days. An argument with a ‘+’ sign leads to the opposite result - files are selected that were accessed during the last X days.

The following command allows you to find all files that have not been updated in the last five days:

$ find / -mtime -5 -print

Below is the command that searches the directory /var/adm files that have been updated within the last three days:

$ find /var/adm -mtime +3 -print

2.1.7. -newer option

If you need to find files that were accessed in the time between updates to two specified files, use the -newer option. The general format for its application is as follows:

Newer old_file! -newer new_file

Sign ' ! ‘ is the logical negation operator. It means: find files that are newer than old_file, but older than new_file.

Let's say we have two files that were updated a little over two days apart:

Rwxr-xr-x 1 root root 92 Apr 18 11:18 age.awk
-rwxrwxr-x 1 root root 1054 Apr 20 19:37 belts.awk

To find all files that were updated later than age.awk, but earlier than belts.awk, run the following command (the use of the -exec option is described below):

$find. -new age.awk ! -newer belts.awk -exec Is -1 () ;
-rwxrwxr-x 1 root root 62 Apr 18 11:32 ./who.awk
-rwxrwxr-x 1 root root 49 Apr 18 12:05 ./group.awk
-rw-r-r- 1 root root 201 Apr 20 19:30 ./grade2.txt
-rwxrwxr-x 1 root root 1054 Apr 20 19:37 ./belts.awk

But what if you need to find files created, say, within the last two hours, but you don’t have a file created exactly two hours ago to compare with? Create such a file! The command touch -t is intended for this purpose, which creates a file with a given timestamp in the format MMDChhmm (month-day-hours-minutes). For example:

$ touch -t 05042140 dstamp
$ls -1 dstamp
-rw-r-r- 1 dave admin 0 May 4 21:40 dstamp

The result will be a file whose creation date is May 4, creation time -21:40 (assuming that current time- 23:40). Now you can use the find command with the -newer option to find all files that have been updated within the last two hours:

$find. -new datamp -print

2.1.8. Option -type

OS UNIX And Linux support Various types files. Finding files of the desired type is done using the find command with the -type option. For example, to find all subdirectories in a directory /etc use this command:

$ find /etc -type d -print

To list all files but not directories, run the following command:

$find. ! -type d -print

Below is the command which is designed to find all symbolic links in a directory /etc.

$ find /etc -type 1 -print

2.1.9. Option -size

During the search process, the file size is specified using the -size option N, Where N- file size in blocks of 512 bytes. Possible arguments have the following meanings: +N- search for files whose size is larger than a specified one, -N- less than specified, N- equal to the given one. If the argument additionally specifies the symbol With, then the size is considered specified in bytes, not in blocks, and if the character k- in kilobytes. To search for files whose size exceeds 1 MB, use the command

$find. -aize -flOOOk -print

The following command searches the directory /home/apache files whose size is exactly 100 bytes:

$ find /home/apache -sixe 100s -print

The following command allows you to search for files larger than 10 blocks (5120 bytes):

$find. -size +10 -print

2.1.10. Option Option -depth

The -depth option allows you to organize the search in such a way that first all files of the current directory (and recursively all its subdirectories) are checked, and only at the end - the entry of the directory itself. This option is widely used when creating a list of files to be archived on tape using the cpio or tar command, since in this case the directory image is first written to the tape and only then the access rights to it are set. This allows the user to archive those directories for which he does not have write permission.
The following command lists all files and subdirectories of the current directory:

$find. -name "*" -print -o -name ".*" -print -depth

Here's what the results of her work might look like:

./.Xdefaults ./.bash_logout ./.bash_profile ./.bashrc ./.bash_nistory ./file ./Dir/filel ./Dir/file2 ./Dir/file3 ./Dir/Subdir/file4 ./Dir/Subdir ./Dir

2.1.11. -mount option

The -mount option of the find command allows you to search for files only on the current file system, excluding other mounted file systems. The following example searches for all files with the extension .xc in the current disk partition:

$ find / -name "*.XC" -mount -print

2.1.12. Searching for files and then archiving them using the cpio command

The cpio command is used primarily to write files to and read from tape. Very often it is used in conjunction with the find command, receiving a list of files from it via a pipe.

Here's how to record directory contents to tape /etc, /home And /apps:

$cd/
$ find etc home appa -depth -print | cpio -ov > dev/rmtO

Option -O The cpio command specifies the mode for writing files to tape. Option -v (verbose- verbal mode) is an instruction to the cpio command to report each file being processed.

Please note that directory names do not have a leading '/' character. In this way, relative path names of the archived directories are set, which, when subsequently reading files from the archive, will allow them to be recreated in any part operating system, and not just in the root directory.

2.1.13. Options -exec and -ok

Let's assume you have found the files you need and want to perform certain actions on them. In this case, you will need the -exec option (some systems only allow ls or ls -1 commands to be executed with the -exec option). Many users use the -exec option to find old files to delete. I recommend running ls instead of rm to make sure the find command finds the files you want to remove.

After the -exec option, specify the command to be executed, followed by curly braces, a space, a backslash, and finally a semicolon. Let's look at an example:

$find. -type f -exec Xa -1 () ;
-rwxr-xr-x 10 root wheel 1222 Jan 4 1993 ./sbin/C80
-rwxr-xr-x 10 root wheel 1222 Jan 4 1993 ./sbin/Normal
-rwxr-xr-x 10 root wheel 1222 Jan 4 1993 ./sbin/Rewid

This searches for regular files, a list of which is displayed on the screen using the ls -1 command.

To find files that have not been updated in a directory /logs within the last five days, and remove them, run the following command:

$ find /log" -type f -mtime +5 -exec rm () ;

You should be careful when moving or deleting files. Use the -ok option, which allows you to execute the mv and rm commands in safe mode(before processing the next file, a confirmation request is issued). In the following example, the find command finds files with the extension .log, and if a file was created more than five days ago, it deletes it, but first asks you to confirm this operation:

$find. -name "*.LOG" -mtime +5 -ok rm () ;
< rm … ./nets.LOG >? at

To delete a file, enter at, and to prevent this action - n.

2.1.14. Additional examples of using the find command

Let's look at a few more examples illustrating the use of the find command. Below is how to find all the files in your starting directory:

$ find ~ -print

Find all files for which the bit is set SUID, the following command allows:

$find. -type f -perm +4000 -print

To get a list of empty files, use this command:

$ find / -type f -size 0 -exec Is -1 () ;

In one of my systems, every day a syslog audit. A number is added to the log file name, which allows you to immediately determine which file was created later and which was created earlier. For example, file versions admin.log numbered sequentially: admin.log.001, admin.log.002 etc. Below is the find command which removes all files admin.log created more than seven days ago:

$ find /logs -name ‘admin.log.1 -atima +7 exec rm () ;

2.2. xargs team

With the -exec option, the find command passes all found files to the specified command, which are processed at one time. Unfortunately, on some systems the length of the command line is limited, so when processing a large number of files you may receive an error message that usually reads: "Too many arguments"(too many arguments) or "Arguments too long"(too large list of arguments). In this situation, the xargs command comes to the rescue. It processes files received from the find command in chunks, rather than all at once.

Consider an example in which the find command returns a list of all the files present on the system, and the xargs command runs the file command on them, checking the type of each file:

$ find / -type f -print I xarge.file
/etc/protocols: English text /etc/securetty: ASCII text

Below is an example that demonstrates searching for dump files whose names the echo command puts into a file /tmp/core.log.

$ find / -name core -print | xarge echo > /tmp/core.log

In the following example, in the directory /apps/audit searches for all files to which other users have full access. chmod command removes write permission for them:

$ find /appe/audit -perm -7 -print | xarge chmod o-w

Our list ends with an example in which grep command searches for files containing the word " device«:

$ find / -type f -print | xarge grep "device"

2.3. Conclusion

The find command is an excellent tool for searching various files using a wide variety of criteria. Thanks to the -exec option, as well as the xargs command, found files can be processed by almost any system command.

One of the most common problems encountered by users new to Linux is searching for necessary files. This tutorial covers using the find command, which allows you to solve this problem and search for files with various filters and parameters.

Search by name

This is the most obvious way to search for files. To search by name, enter:

Find -name "name"

This query will be case sensitive, meaning “file” and “File” will be treated as different names.

To search by name, case insensitive, enter:

Find -iname "name"

If you need to find all files that do not match a certain pattern, you can invert the search using the “-not” or “!” option. Using "!" You need to escape the character so that bash doesn't try to interpret it before find runs:

Find -not -name "name to exclude"

Find\! -name "name to exclude"

Search by type

You can specify the type of files you need to find using the -type parameter. It works like this:

Find -type type_descriptor request

Here are the most common type descriptors:

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

For example, if we need to find all character devices on the system, we can run the following command:

And this way we can search for all files that end in “.conf”:

Find / -type f -name "*.conf"

Search by time and size

Find provides a number of ways to filter results by size and time.

Search by size

Filtering by size is done using the “-size” parameter.

After the size value, you must specify a suffix indicating the units of measurement. Here are some of the most common options:

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

To find all files that are exactly 100 bytes in size, enter:

Find / -size 100c

To search for all files smaller than 100 bytes, we can use the following form:

Find / -size -100c

To search for files larger than 500 megabytes, you can use the following command:

Find / -size +500M

Search by time

Linux stores access time, modification time, and modification time.

  • Access Time: The last time the file was read or written to.
  • Modification Time: The time the file's contents were last modified.
  • Modification Time: The time the metadata in the file's inode was last modified.

To filter by these values, we can use the options "-atime", "-mtime" and "-ctime", respectively, as well as the plus and minus symbols to find files with an earlier or later time, similar to filtering by size.

The value of these parameters indicates how many days ago the search should be performed.

To search for files whose contents were changed yesterday, enter:

Find / -mtime 1

If we need files that were accessed yesterday and later, we can use the command:

Find / -atime -1

To retrieve files whose metadata has been changed more than three days ago, use the following command:

Find / -ctime +3

There are also Extra options, which allow you to specify minutes instead of days. This command lists files modified in the last minute:

Find / -mmin -1

Additionally, find can compare against a given file and return all files that are newer:

Find / -newer myfile

Search by owner and permissions

Using the "-user" and "-group" parameters, you can search for files by owner or group, respectively. To find the user's "syslog" file, you need to enter:

Find / -user syslog

Similarly, you can search for files in the “shadow” group:

Find / -group shadow

You can also search for files with specific permissions.

If we need to match a precise set of permissions, the following form is used:

Find / -perm 644

If you need to find all files with resolutions not lower than the specified ones, you need to enter:

Find / -perm -644

All files with additional permissions will meet this criterion. For example, in this case it will correspond to a file with permissions “744”.

Filtering by depth

For this section, we will need to create a three-level directory structure in the temporary directory with ten directories on the first level. Each directory (including temporary) will have ten subdirectories and ten files.

Let's create the structure by running the following commands:

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

You can use the ls and cd commands to check the structure. Having understood the organization, you need to return to the test directory:

Cd ~/test

Now let's try to find in this structure specific files. Let's start with an example of a regular search by name:

Find -name file1

There are a lot of results. If we translate the output to a counter, we will see that there are 1111 such files in total:

Find -name file1 | wc -l 1111

In most cases these results are redundant. Let's try to narrow down the search.

You can set the maximum search depth in the top-level search directory:

Find -maxdepth number -name name

To find "file1" only in directories "level1" and above, you need to specify a maximum depth of 2 (1 for the top-level directory and 1 for level 1 directories):

Find -maxdepth 2 -name file1

If you find an error, please highlight a piece of text and click Ctrl+Enter.

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

For search hidden files in the 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.

Very often you urgently need to find some file in the file system, but you have no idea where it is. And if GUI utilities for searching a file are boring or you don’t have a GUI installed at all or you don’t use it at all, then extensive commands for searching files, folders and parts of a file in Linux will come to the rescue.

Search for a file by name in the database.
The locate command can be used to search for file(s) based on part of the file name. The command scans the name database and returns the path to the file(s) you are looking for. We recommend running the command with the -i option: locate -i for a case-insensitive search.
Example:

subsanek@subsanek-laptop:~$ locate -i .ogg
/home/subsanek/unknown - unknown/01 - unknown 1 - ???.ogg
/usr/local/Zend/ZendStudio-7.1.2/docs/PHPmanual/book.oggvorbis.html
/usr/local/Zend/ZendStudio-7.1.2/docs/PHPmanual/intro.oggvorbis.html
/usr/share/kde4/apps/bball/bounce.ogg
/usr/share/kde4/apps/klettres/en_GB/alpha/a.ogg
/usr/share/kde4/apps/klettres/en_GB/alpha/b.ogg
/usr/share/kde4/apps/klettres/en_GB/alpha/c.ogg
(truncated)


-calling the command found all files in the system with the ogg extension.
locate searches for files very quickly, but it's just looking at a list of names from the database and if the file was created recently, there's a good chance it won't be found.
Database update.
You can update the locate command database with the command (as a superuser):
updatedb
Human-readable output.
Often the locate command can produce many thousands of results that will simply flash in front of the screen and do nothing for your eyes, to avoid this you can redirect the output result to a container:
locate -i .ogg | less
You can also set how many results you want to display using the -n option:
locate -i .ogg -n 10
-will display the first 10 results.

Search for files with real scanning.
The find command scans the file system to find a file, making this tool slow but effective.
To search by name, you must specify the -name key
Example:
find -name filename.txt
By default, find searches recursively in the current directory.

Search for text using a fragment from the text.
The legendary grep command can serve almost any purpose. I like to use it not only to search for the necessary files in the source directory. You can also use grep to search for regular expressions.
Command prototype:
grep "search pattern" file_to_search
Example:
grep -R "text" /
-the command will search recursively in all text files system word text.
Grep has an impressive number of options that may be needed quite often:

subsanek@subsanek-laptop:~$ grep --help
Usage: grep [KEY]... PATTERN [FILE]...
Search for PATTERN in each FILE or standard input.
By default, PATTERN is a simple regular expression (BRE).
Example: grep -i "hello world" menu.h main.c

Selecting the type of regular expression and its interpretation:
-E, --extended-regexp PATTERN - extended regular expression (ERE)
-F, --fixed-regexp PATTERN - fixed length strings, delimited
newline character
-G, --basic-regexp PATTERN - simple regular expression (BRE)
-P, --perl-regexp PATTERN - Perl regular expressions
-e, --regexp=PATTERN use PATTERN to search
-f, --file=FILE take PATTERN from FILE
-i, --ignore-case ignore case difference
-w, --word-regexp PATTERN must match all words
-x, --line-regexp PATTERN must match the entire line
-z, --null-data lines are separated by a byte with zero value, but not
end-of-line character

Additionally:
-s, --no-messages suppress error messages
-v, --revert-match select unmatched lines
-V, --version print version information and exit
--help show help and exit
--mmap use memory mapping (mmap) whenever possible

Output Control:
-m, --max-count=NUM stop after the specified NUMBER of matches
-b, --byte-offset print offset in
bytes
-n, --line-number print line number along with output lines
--line-buffered reset buffer after each line
-H, --with-filename print the filename for each match
-h, --no-filename do not start output with filename
--label=LABEL output LABEL as the file name for
standard input
-o, --only-matching show only the part of the string that matches the PATTERN
-q, --quiet, --silent suppress all normal output
--binary-files=TYPE assume binary file is TYPE:
binary, text or without-match.
-a, --text same as --binary-files=text
-I same as --binary-files=without-match
-d, --directories=ACTION how to handle directories
ACTION can be read (read),
recurse (recursively), or skip (skip).
-D, --devices=ACTION how to handle devices, FIFOs and sockets
ACTION can be "read" or "skip"
-R, -r, --recursive same as --directories=recurse
--include=F_TEMPLATE process only files matching F_TEMPLATE
--exclude=F_PATTERN skip files and directories,
falling under F_TEMPLATE
--exclude-from=FILE skip files matching the pattern
files from FILE
--exclude-dir=PATTERN directories matching PATTERN
will be missed
-L, --files-without-match print only FILE names without matches
-l, --files-with-matches print only FILE names with matches
-c, --count print only the number of matches
lines per FILE
-T, --initial-tab align with tabs (if necessary)
-Z, --null print byte 0 after the FILE name

Context management:
-B, --before-context=NUM print the NUMBER of lines of the preceding context
-A, --after-context=NUM print the NUMBER lines of subsequent context
-C, --context[=NUM] print the NUMBER of context lines,
--color[=WHEN],
--colour[=WHEN] use markers to differentiate matching
lines; WHEN it can be always (always),
never (never), or auto (automatically)
--color, --colour use markers to distinguish matching lines
-U, --binary do not remove CR characters at the end of the line (MSDOS)
-u, --unix-byte-offsets output offset as if there are no CRs (MSDOS)

Instead of egrep, grep -E is supposed to be run. Instead of fgrep, grep -F is assumed.
It is better not to run as egrep or fgrep.
When FILE is not specified, or when FILE is -, then standard input is read.
If fewer than two files are specified, -h is assumed. When you find
matches, the program exit code will be 0, and 1 if not. If
errors, or if the -q option is not specified, the exit code will be 2.