DEV Community

howtouselinux
howtouselinux

Posted on • Updated on

Find files by name in Linux


Linux find command is a powerful tool that can be used to locate and manage files and directories based on a wide range of search criteria.

This means that we can provide it with a set of directories (or files) or filters, and it will apply appropriate actions to them and also to any directories and files within them.

In this post, we will use the find command to find files in a directory tree by file name.

The syntax is very straightforward. Give the name of the directory tree to search through, and use the `-name' option followed by the name you want to find.

Here are more examples of finding files by file name in Linux.

To list all files on the system whose file name is top, type:

$ find / -name top
Enter fullscreen mode Exit fullscreen mode

This command will search all directories on the system to which you have access; if you don't have execute permission for a directory, find will report that permission is denied to search the directory.

The -name option is case sensitive; use the similar `-iname' option to find name regardless of case.

To list all files on the system whose file name is top, regardless of case, type:

$ find / -iname top
Enter fullscreen mode Exit fullscreen mode

This command would match any files whose name consisted of the letters top, regardless of case -- including Top, top, and TOP.

Use file expansion characters to find files whose names match a pattern. Give these file name patterns between single quotes.

To list all files on the system whose names begin with the characters top, type:

$ find / -name 'top*' 
Enter fullscreen mode Exit fullscreen mode

To list all files whose names begin with the three characters top followed by exactly three more characters, type:

$ find / -name 'top???' 
Enter fullscreen mode Exit fullscreen mode

To list all files whose names begin with the three characters top followed by five or more characters, type:

$ find / -name 'top?????*' 
Enter fullscreen mode Exit fullscreen mode

To list all files in your home directory tree that end in .tex', regardless of case, type:

$ find ~ -iname '*.tex' 
Enter fullscreen mode Exit fullscreen mode

To list all files in the /usr/share' directory tree with the text farm' somewhere in their name, type:

$ find /usr/share -name '*farm*' 
Enter fullscreen mode Exit fullscreen mode

Use -regex in place of -name to search for files whose names match a regular expression, or a pattern describing a set of strings

To list all files in the current directory tree whose names have either the string net or comm' anywhere in their file names, type:

$ find . -regex '.*\(net\|comm\).*' 
Enter fullscreen mode Exit fullscreen mode

NOTE: The `-regex' option matches the whole path name, relative to the directory tree you specify, and not just file names.

Top comments (0)