How to find files by name
How to use the find
command to find files by matching a pattern in
the name
and (optionally) limit the search only to the first level
One of the most common operations on a Linux OS is to search for files, given a pattern that must
match the
file name. For example, we may want to identify all the files with a given extension in a directory
(also recursively), or all the files starting with a prefix or containing a substring. The
find
command can help us and it is very easy to use. It requires the target directory (from which we
start the search) and a regular expression to match the file name. For example, if we already are in
the
target directory, we will use the “.” to identify it. Suppose we are looking for all the XML files
in the
current directory and sub-directories (find
is recursive by default):
find . -name '*.xml'
If we want to limit the search only to the current directory, without searching recursively
in sub-directories, we can use the maxdepth option:
find . -maxdepth 1 -name '*.xml'
If we want to iterate over the results of the
find
command, we can use a
for
as explained
here.