Often you may want to copy all files with a specific extension from all subdirectories into a new directory in Bash.
You can use the following syntax to do so:
find . -name \*.txt -exec cp {} /c/users/bobbi/data2 \;
This particular example will copy all files from all subdirectories in the current directory that contain a .txt. extension into a new directory located at c:/users/bobbi/data2.
Here is what the various commands do:
- find . -name \*.txt: Match only the files with .txt extensions from all subdirectories
- -exec cp {}: Copy each of the matched files to the new directory
The following example shows how to use this syntax in practice.
Example: Copy All Files with Specific Extension from All Subdirectories in Bash
Suppose that we would like to copy all files from each subdirectory in our current directory that contain a .txt extension into a new directory.
We can use the find command with the following syntax to first find all files that have a .txt extension in each subdirectory:
find . -name \*.txt
The following screenshot shows how to use this syntax in practice:

From the output we can see that the current directory contains two subdirectories that contain various files with .txt extensions:
- Subdirectory east_data
- teams1.txt
- teams2.txt
- teams3.txt
- Subdirectory west_data
- teams4.txt
- teams5.txt
Suppose that we would like to copy all of these files with .txt extensions into a new directory located at the following path:
- c:/users/bobbi/data2
We can use the following syntax to do so:
find . -name \*.txt -exec cp {} /c/users/bobbi/data2 \;
The following screenshot shows how to use this syntax in practice:

Notice that when we use the ls statement to view the files in the new directory we can see that each of the files with a .txt extension from the current directory have been copied into this new directory.
Note: Feel free to change .txt to any other extension that you would like.
Related Tutorials
The following tutorials explain how to perform other common tasks in Bash:
Bash: How to Copy and Rename a File
Bash: How to Copy a File to Multiple Directories
Bash: Copy Multiple Specific Files from One Folder to Another
