To find a file in a directory and its subdirectories, you can use the find /path/to/directory -name filename
command, or if you want to find files of different extensions, use the find command with wildcards (.*) on the Linux command line.
Here are some approaches of Linux commands to find a file in the directory and subdirectory on the command line:
- Approach 1: Using Find Command
- Approach 2: Using Wildcards with Find Command
- Approach 3: Using Multiple Wildcards with Find Command
Approach 1: Using Find Command
Find command is available in Linux OS, To find a file in a directory and its subdirectories using the find /path/to/directory -name filename
command on the command line, you can use like this:
find /path/to/directory -name filename
E.g. if you have a directory named “/home/document/” and all its subdirectories, you want to find hello.txt, you can use this command on command line:
find /home/document hello.txt
Approach 2: Using Wildcards with Find Command
To use wildcards with find /path/to/directory -name "*.txt"
command on Linux command line, you can search multiple files in a directory and its subdirectories, for this you can use the command:
find /path/to/directory -name "*.txt"
Your directory and subdirectories are files of more than one extension, and for example, if you want to search only file of the “.txt” extension, you can use the wildcards with the find command:
find /home/document -name "*.txt"
In this command, the “.” specifies the current directory, and the “-name” option specifies that we want to match filenames based on their name. The “*.txt” expression uses the asterisk wildcard to match any string of characters followed by the “.txt” extension.
For another example, to find all the directories and subdirectories, use wildcards at beginning and end of the directory name:
find -name "*tuts*"
Approach 3: Using Multiple Wildcards with Find Command
To use multiple wildcards such as .txt, .php, .json, etc
with the find command to search a file in the directory and its subdirectories linux, this you can use this command:
find . \( -name "*.ext1" -o -name "*.ext1" \)
Here “-o” option specifies that want to match files that meet either of the two criteria specified by the expressions in parentheses. The parentheses are used to group the expressions.
To find multiple extension such as “.txt”, and “.php” in a directory and subdirectories, you need to use the command on the Linux command line:
find . \( -name “*.txt” -o -name “*.php” \)
Here is the video guide on how to find a file in directory and subdirectory on linux command line:
Conclusion
That’s it; you have learned 3 ways how to search a file in directory or folder and its subdirectory.