How to Find and Copy Certain Type of Files in Linux

Question: How do I find files of a certain type and copy those files to a different directory in Linux?

Suppose you are in a situation where you have to find a certain type of files in a given directory and copy them to another directory. There might be other ways to do this but the most obvious way would be to use a combination of find and exec command.

For example, if you have to find all the XML files in the current directory and copy them, you can use something like this in the Linux command line:

find . -type f -name "*.xml" -exec cp {} <destination_directory> \;

To explain the above command:

find is the command to find files and directories

-type f tells the command to find only files (not directories)

-name “*.xml” tells the find command to look for files with names that end with .xml

-exec cp tells to execute the cp command to copy files from source (in this case output of find command) to the destination directory

{} replaces the name of the files found by ‘find’ command

<destination_directory> is the directory where matching files will be copied

\; is used to tell that the commands to be executed are finished, and to run the command again for the next match

In order to generalize the above command, you can use the below command template:

Share this:

Other Linux Command Tips

About Abhishek Prakash

I am a software developer by profession and a Linux user by passion. I also co-founded It's FOSS. Linux Quick Tips is my quick notebook where I share quick Linux command tricks, some basic and some advanced.