How to search for files in Linux using the find command. How to find a file in Linux Bash find options


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: ,

When working in any operating system, sometimes there is a need to use tools to quickly search for a particular file. This is also relevant for Linux, so all possible ways to search for files in this OS will be discussed below. Both file manager tools and commands used in "Terminal".

If you need to specify many search parameters to find the file you need, then the command find irreplaceable. Before considering all its variations, it is worth going through the syntax and options. It has the following syntax:

find path option

Where path- this is the directory in which the search will take place. There are three main options for specifying the path:

  • / — search in the root and adjacent directories;
  • ~ — search by home directory;
  • ./ — search in the directory in which the user is currently located.

You can also specify the path directly to the directory itself where the file is supposedly located.

Options find there are a lot, and it is thanks to them that you can perform flexible search settings by setting the necessary variables:

  • -name- conduct a search using the name of the element you are looking for as a basis;
  • -user- search for files that relate to a specific user;
  • -group- search for a specific group of users;
  • -perm- show files with the specified access mode;
  • -size n- search based on the size of the object;
  • -mtime +n -n- search for files that have changed more than ( +n) or less ( -n) days ago;
  • -type- search for files of a specific type.

There are also many types of elements you are looking for. Here is their list:

  • b- block;
  • f- ordinary;
  • p- named pipe;
  • d- catalogue;
  • l- link;
  • s- socket;
  • c- symbolic.

After a detailed analysis of the command syntax and options find You can go directly to illustrative examples. Due to the abundance of options for using the command, examples will not be given for all variables, but only for the most used ones.

Method 1: Search by name (-name option)

Most often, users use the option to search the system -name, so that’s where we’ll start. Let's look at a few examples.

Search by extension

Let's say you need to find a file on the system with the extension ".xlsx", which is located in the directory "Dropbox". To do this you need to use the following command:

find /home/user/Dropbox -name "*.xlsx" -print

From its syntax we can say that the search is carried out in the directory "Dropbox" ("/home/user/Dropbox"), and the desired object must have the extension ".xlsx". An asterisk indicates that the search will be carried out on all files of this extension, without taking into account their name. "-print" indicates that search results will be displayed.

Search by file name

For example, you want to search in a directory "/home" file with name "lumps", but its extension is unknown. In this case, you need to do the following:

find ~ -name "lumpics*" -print

As you can see, the symbol used here is «~» , which means the search will take place in the home directory. After option "-name" the name of the searched file is indicated ( "lumps*"). The asterisk at the end means that the search will be carried out only by name, without taking into account the extension.

Search by first letter of name

If you only remember the first letter of the file name, there is a special command syntax that will help you find it. For example, you want to find a file that starts with the letter from "g" before "l", and you don't know what directory it is in. Then you need to run the following command:

find / -name "*" -print

Judging by the “/” symbol that comes immediately after the main command, the search will be carried out starting from the root directory, that is, throughout the entire system. Next, part «*» means that the searched word will begin with a certain letter. In our case from "g" before "l".

By the way, if you know the file extension, then after the symbol «*» you can indicate it. For example, you need to find the same file, but you know that it has the extension ".odt". Then you can use this command:

find / -name "*.odt" -print

Method 2: Search by access mode (-perm option)

Sometimes you need to find an object whose name you do not know, but you know what access mode it has. Then you need to use the option "-perm".

It is quite simple to use; you just need to specify the search location and access mode. Here is an example of such a command:

find ~ -perm 775 -print

That is, the search is carried out in the home section, and the objects being searched will have access 775 . You can also write a “-” symbol in front of this number, then the found objects will have permission bits from zero to the specified value.

Method 3: Search by user or group (options -user and -group)

Every operating system has users and groups. If you want to find an object belonging to one of these categories, you can use the option "-user" or "-group", respectively.

Find a file by its username

For example, you need to find in the directory "Dropbox" file "Lamps", but you don’t know what it’s called, you just know that it belongs to the user "user". Then you need to run the following command:

find /home/user/Dropbox -user user -print

In this command you specified the required directory ( /home/user/Dropbox), indicated that you need to look for a file belonging to the user ( -user), and indicated which user this file belongs to ( user).

Searching for a file by its group name

Searching for a file that belongs to a specific group is just as easy - you just need to replace the option "-user" to option "-group" and indicate the name of this group:

find / -groupe guest -print

That is, you indicated that you want to find a file in the system that belongs to the group "guest". The search will occur throughout the system, this is indicated by the symbol «/» .

Method 4: Search for a file by its type (-type option)

Finding an element of a certain type in Linux is quite simple, you just need to specify the appropriate option ( -type) and designate the type. At the beginning of the article, all the type designations that can be used for searching were listed.

For example, you want to find all block files in your home directory. In this case your command would look like this:

find ~ -type b -print

Accordingly, you indicated that you are searching by file type, as evidenced by the option "-type", and then determined its type by putting the block file symbol - "b".

In the same way, you can display all directories in the desired directory by entering the symbol in the command "d":

find /home/user -type d -print

Method 5: Search file by size (-size option)

If all you know about a file is its size, then even that may be enough to find it. For example, you want to find a 120 MB file in a certain directory, to do this, do the following:

find /home/user/Dropbox -size 120M -print

As you can see, the file we need was found. But if you don't know what directory it is in, you can search the entire system by specifying the root directory at the beginning of the command:

find / -size 120M -print

If you know the approximate size of the file, then there is a special command for this case. You need to register in "Terminal" the same thing, just put a sign before indicating the file size «-» (if you need to find files smaller than the specified size) or «+» (if the size of the file you are looking for is larger than the specified size). Here is an example of such a command:

find /home/user/Dropbox +100M -print

Method 6: Find a file by modification date (option -mtime)

There are times when it is most convenient to search for a file by the date it was modified. On Linux, this is done using the option "-mtime". It’s quite simple to use, let’s look at everything using an example.

Let's say in the folder "Images" we need to find objects that have been subject to changes in the last 15 days. Here's what you need to write in "Terminal":

find /home/user/Images -mtime -15 -print

As you can see, this option shows not only files that have changed during the specified period, but also folders. It also works in the opposite direction - you can find objects that were changed after the specified date. To do this, you need to enter the sign before the digital value «+» :

find /home/user/Images -mtime +10 -print

GUI

The graphical interface makes life much easier for beginners who have just installed a Linux distribution. This search method is very similar to the one in Windows, although it cannot provide all the advantages that it offers "Terminal". But first things first. So, let's look at how to search for files in Linux using the system's graphical interface.

Method 1: Search through the system menu

Now we will look at how to search for files through the Linux system menu. The actions taken will be performed in the Ubuntu 16.04 LTS distribution, but the instructions are common for everyone.

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 options offered is 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 path_name -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 Search 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 to which other users have 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 the current time is 23:40). You can now 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 file types. 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 all files of the current directory (and recursively all its subdirectories) are checked first, 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 of the 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 run the mv and rm commands in safe mode (you will be prompted for confirmation before processing the next file). 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 () ;

One of my systems creates a system audit log every day. 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. The chmod command removes write permission for them:

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

Rounding out our list is an example in which the 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.

You are probably familiar with this problem: There is a file, and you don’t remember where you put it.

In this case, the find command is convenient. How to use it? Of course, this utility comes with a large man page, but we will look at some typical cases. Browse the directory tree, starting with the current one, and find the file lostfile.txt:

If you are searching through a large directory tree, the find command can be quite slow. Sometimes it is more convenient to use the locate command. It does not look for the file directly in the file system, but looks through its database. This method is much faster, but the database may become outdated. On some distributions this database is modified every night. You can manually run the updatedb command from time to time to modify it. locate searches for substrings:

The number of misspellings allowed depends on the length of the filename, but can be set using the -t option. To allow a maximum of 2 errors and use a special character, simply type:

Directory tree overview

Sometimes you need to get an overview of a directory tree. For example, let's say you received a new CD-ROM and would like to know what's on it. You can simply use ls -R . Personally, I prefer one of the following methods for readability. Tree (sunsite.unc.edu/pub/Linux/utils/file/tree-1.2.tgz) displays a directory tree as a diagram.

Or use good old find . The Gnu version of find that usually ships with Linux has the ability to change the output format to display, for example, the file name and its size:

You can use a small perl procedure that works with the ls command, which does similar things. It can be downloaded from here: lsperl.gz. There are many other directory tree browsing utilities, but for most cases these are sufficient.

Search files by content (search for text strings in files).

The standard utilities for searching for text strings in files are grep/egrep for regular expression searches and fgrep for literal string searches. To search for an expression in all files in the current directory, simply type:

If you find it difficult to remember these long commands, use a small script that can be downloaded from here: grepfind.gz. The script also removes non-printable characters from the search string so that you do not accidentally receive a binary file as a result of an egrep search.

A very interesting search program is agrep. Agrep works basically like egrep, but allows spelling errors to be searched. To search for an expression and allow up to 2 spelling errors, type:

After this you can search for a string in all files that were previously indexed

glimpse -i -2 "search exprission"

glimpse - also allows spelling errors (like agrep) and -2 indicates that two errors are allowed. glimpse available at

    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 items. 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.






2024 gtavrl.ru.