Linux find file by name in directory

Find Files by Name in Linux

Finding files by their name is one of the most common scenarios of finding files in Linux. Here are a few examples to help.

Most often, you are looking for a file on Linux and you do not exactly know its true location on the system disk.

There are multiple ways to find files in the Linux command line. Most common and most reliable way is to use the find command.

The find command is extremely versatile and has way too many usages but here I’ll focus on finding files by their name.

I’ll explain how to use the ‘find’ command for:

  • Searching files using their name
  • Searching files with their exact name
  • Searching files for a particular pattern
  • Searching multiple files
  • Excluding certain files from the search results.

Besides these, I’ll also show how to use the grep command with the output from the find command. Let’s first start with an overview of the find command.

The utility ‘find’ looks for files that match a certain set of parameters like the file’s name, its modification date, its extension, etc. It has the following format:

If the file path is not specified, it searches in the current directory and its sub-directories.

Searching for Files Using their Name

Looking for a file with its name is a commonly used operation with the find command. The -iname option looks for a file regardless of its case.

For example, suppose you have two files abc.txt and ABC.txt. Both of them have the same name but different cases. Using the find command, you get both files in the results:

Find files with their name

Searching for Files Using their Exact Name

The -name option is case-sensitive in contrast to the -iname option, so you are going to get files with the exact name.

For example, let us look for a file with the name abc.txt :

Find files with exact name

The name of the file can be composed of wildcards as you will see later in this guide.

Searching for Files With a Particular Pattern

You can also filter files that follow a given pattern. For that, you can use wildcards.

Say, for instance, you are looking for all the configuration files on your system that end with the ‘.conf’ extension:

find /etc -type f -name "*.conf" | grep client.conf

Find files with their extension

In the same way, you can also search for files with the same name but with any extension of three characters as:

Читайте также:  Linux операционная система чем лучше window

Find files with any extension

If you have several file names that contain a common string, say ‘VM’, the find command in this scenario will be as:

Find files with a matching pattern

So far, we have used a single directory (the home directory) with the ‘find’ command.

You can also search in multiple directories by specifying them on the CLI:

find ~/Desktop/example1/ ~/Desktop/example2/ -name 'abc*.*'

Find files in multiple directories

Searching for Multiple Files and Multiple Patterns

Suppose you want to find multiple files in a directory having .msi and .txt as file types.

Here you need to use both the name and type options on the CLI as:

find -type f \( -name "*.txt" -o -name "*.msi" \)

Search for multiple files

In a similar approach, you can extend the above command for more files by using extra -o options.

Excluding Certain Files from the Search Results

The find command can also exclude certain types of files from the search result:

find -name '*abc*' -type f \( ! -name '*.msi' \)

Exclude certain files from find search results

Here, the ‘find’ command will look for all the files having ‘abc’ string in their name. However, it will filter out the .msi type of files.

Other Common Examples of the ‘find’ Command

You have more options that can be used with the ‘find’ command. Let me share a few such examples:

System reporting low disk space? Find bigger files like this:

Using the above command, you can find files occupying more than 2000 Megabytes of space.

In case you need to save your findings for later investigation, redirect it to a file:

find -name '*abc*' -type f \( ! -name '*.msi' \) > mysearch.txt

Save the result of the find command

The type option with the find command opens many opportunities.

You can combine it with different file descriptors for different types of files. For example, ‘f’ for a regular file, ‘d’ for a directory, ‘l’ for a symbolic link, etc.

find /var/log -type f -name "*.log" 

Conclusion

In this guide, I explained how to search for files by their names using the find command. You saw multiple ways to narrow down the search path and most importantly, how to incorporate the ‘wildcards’ for pattern searching.

There are many more uses of the find command. Like you can use it to find recently modified files. Here are a few more common examples if you are interested.

You can always search man pages to get extensive insights into the various options with the ‘find’ command.

Источник

Find Files in Linux Using the Command Line

Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.

When you have to find a file in Linux, it’s sometimes not as easy as finding a file in another operating system. This is especially true if you are running Linux without a graphical user interface and need to rely on the command line. This article covers the basics of how to find a file in Linux using the CLI. The find command in Linux is used to find a file (or files) by recursively filtering objects in the file system based on a simple conditional mechanism. You can use the find command to search for a file or directory on your file system. By using the -exec flag ( find -exec ), matches, which can be files, directories, symbolic links, system devices, etc., can be found and immediately processed within the same command.

Читайте также:  Linux show memory info

Find a File in Linux by Name or Extension

Use find from the command line to locate a specific file by name or extension. The following example searches for *.err files in the /home/username/ directory and all sub-directories:

find /home/username/ -name "*.err" 

Using Common find Commands and Syntax to Find a File in Linux

find expressions take the following form:

find options starting/path expression 
  • The options attribute will control the find process’s behavior and optimization method.
  • The starting/path attribute will define the top-level directory where find begins filtering.
  • The expression attribute controls the tests that search the directory hierarchy to produce output.

Consider the following example command:

find -O3 -L /var/www/ -name "*.html" 

This command enables the maximum optimization level (-O3) and allows find to follow symbolic links ( -L ). find searches the entire directory tree beneath /var/www/ for files that end with .html .

Basic Examples

Command Description
find . -name testfile.txt Find a file called testfile.txt in current and sub-directories.
find /home -name *.jpg Find all .jpg files in the /home and sub-directories.
find . -type f -empty Find an empty file within the current directory.
find /home -user exampleuser -mtime -7 -iname «.db» Find all .db files (ignoring text case) modified in the last 7 days by a user named exampleuser.

Options and Optimization for find

The default configuration for find will ignore symbolic links (shortcut files). If you want find to follow and return symbolic links, you can add the -L option to the command, as shown in the example above.

find optimizes its filtering strategy to increase performance. Three user-selectable optimization levels are specified as -O1 , -O2 , and -O3 . The -O1 optimization is the default and forces find to filter based on filename before running all other tests.

Optimization at the -O2 level prioritizes file name filters, as in -O1 , and then runs all file-type filtering before proceeding with other more resource-intensive conditions. Level -O3 optimization allows find to perform the most severe optimization and reorders all tests based on their relative expense and the likelihood of their success.

Command Description
-O1 (Default) filter based on file name first.
-O2 File name first, then file type.
-O3 Allow find to automatically re-order the search based on efficient use of resources and likelihood of success.
-maxdepth X Search current directory as well as all sub-directories X levels deep.
-iname Search without regard for text case.
-not Return only results that do not match the test case.
-type f Search for files.
-type d Search for directories.
Читайте также:  Web media player linux

Find a File in Linux by Modification Time

The find command contains the ability to filter a directory hierarchy based on when the file was last modified:

find / -name "*conf" -mtime -7 find /home/exampleuser/ -name "*conf" -mtime -3 

The first command returns a list of all files in the entire file system that end with the characters conf and modified in the last seven days. The second command filters exampleuser user’s home directory for files with names that end with the characters conf and modified in the previous three days.

Use grep to Find a File in Linux Based on Content

The find command can only filter the directory hierarchy based on a file’s name and metadata. If you need to search based on the file’s content, use a tool like grep . Consider the following example:

find . -type f -exec grep "example" '<>' \; -print 

This searches every object in the current directory hierarchy ( . ) that is a file ( -type f ) and then runs the command grep «example» for every file that satisfies the conditions. The files that match are printed on the screen ( -print ). The curly braces ( <> ) are a placeholder for the find match results. The <> are enclosed in single quotes ( ‘ ) to avoid handing grep a malformed file name. The -exec command is terminated with a semicolon ( ; ), which should be escaped ( \; ) to avoid interpretation by the shell.

How to Find and Process a File in Linux

The -exec option runs commands against every object that matches the find expression. Consider the following example:

find . -name "rc.conf" -exec chmod o+r '<>' \; 

This filters every object in the current hierarchy ( . ) for files named rc.conf and runs the chmod o+r command to modify the find results’ file permissions.

The commands run with the -exec are executed in the find process’s root directory. Use -execdir to perform the specified command in the directory where the match resides. This may alleviate security concerns and produce a more desirable performance for some operations.

The -exec or -execdir options run without further prompts. If you prefer to be prompted before action is taken, replace -exec with -ok or -execdir with -okdir .

How to Find and Delete a File in Linux

To delete the files that end up matching your search, you can add -delete at the end of the expression. Do this only when you are positive the results will only match the files you wish to delete.

In the following example, find locates all files in the hierarchy starting at the current directory and fully recursing into the directory tree. In this example, find will delete all files that end with the characters .err :

More Information

You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

This page was originally published on Monday, October 25, 2010.

Источник

Оцените статью
Adblock
detector