In Linux, the command ‘cp‘, which standards for ‘Copy‘ is used to copy files and folders to another folder. It is available by default in Linux as part of the GNU Coreutils set of tools.
The most basic use of the cp command is to specify the files to be copied as the arguments and to specify the target folder as the last argument.
$ cp file1 file2 file3... fileN target_folder/
Copy Files with Specific File Extensions
You can even copy files of the same file extension (Eg. .txt
, .jpg
, .mp4
) together using wildcard characters, as shown below:
$ cp *.jpg *.mp4 *.mp3 media/
This will copy all the JPEG images, MP3, and MP4 multimedia files to the folder ‘media‘. Note that this can only be used for files. If you try to copy folders in the above format, it throws a warning that the folder is ‘Not empty‘.
To copy folders, we have to specify the '-r'
(recursive) flag. Recursive means that all the files in that folder, the files in the subfolders, and so on, will all be copied.
$ cp -r folder1/ folder2/ file1 file2 target_folder/
However, there is no way within ‘cp’ to copy files of a specific extension recursively. Whenever '-r'
is specified, the program always considers all files in the subfolders for copying.
Find and Copy Files with File Extension
To achieve this, we use the find command, which is simply used to search for files and folders in Linux based on the parameters of the file or folder: filename, extension, size, etc.
We will make use of the find command to recursively locate files with a specific file extension and then pass this output to cp command to copy them.
Syntax to locate files of a specific extension using find command is:
$ find <folder_to_search> -name ‘*.<extension>’
For example, to locate all JPG files recursively in the current folder:
$ find . -name '*.jpg'
Finally, we have to pipe this output to the cp command. To do this, we use the ‘xargs’ command to make ‘cp’ consider the output of ‘find’ as its arguments. Also, we use the '-t'
flag of cp, to specify the target directory, without which the program considers the output of ‘find’ as the target directory.
$ find . -name '*.jpg' | xargs cp -t Pictures2/
Thus, all the files of the extension '.jpg'
have been copied to the folder ‘Pictures2’.
Conclusion
In this article, we learned how to copy files with a specific extension recursively in Linux. Note that this method is useful if you are dealing with a smaller number of files. For a huge number of files (for example, in tens of thousands), you need to use a different approach to copy the files recursively.
If you have any questions or feedback, let us know in the comments below.