Command-line is a powerful tool because we can redirect the output of a command to another command in a single line, and in this case, we will redirect the output of find command to the cp command. In this tutorial, I will show you how can you exclude several files with a specific extension while copying from source to destination. We will do this with the help of find and cp command. First, let’s understand how both of them function :
The cp command
cp command is used to copy files and folders in the command line in Linux. You can simply type
cp file1 file2 file3 destination/folder
To copy files to a destination folder. Or if you want to copy a folder to some other destination, you have to use the
-r (recursive) option as follows :
cp -r directory1/ directory2/ desitination/folder
The recursive option implies that all the folders and subfolders that are stored in the given directory will be also copied. But, there is no method using which we can use the cp command alone to exclude a file extension (let’s say mp3) while copying. That’s where we will need the find command.
Also read: cp command in Linux
The find command in Linux can be used to list out all the files and folders containing a specific name or characters. We can use this feature to our advantage by searching for all the files and neglecting files with certain extensions. For example, in the LFD directory we have certain pictures, mp3s, and text files, now to list all the mp3 files, we will have to type :
find . -name "*.mp3"
And if we wish to list all the files except mp3s, we can just add an exclamation mark (!)
find . ! -name "*.mp3"
The output of this command also lists all the directories, to exclude them from the search result, we will have to add
-type f option, here f stands for files.
find . ! -name "*.mp3" -type f
Great! Now let’s use this command to copy all the files except mp3s from the current directory to another location with the help of the piping feature of the command line.
Copy all the files except…
In addition to piping, we need to use the ‘xargs’ command to make ‘cp’ consider the output of ‘find’ command as an argument. We will also add -t option to the cp command to set the target folder somewhere else, otherwise, it will simply copy all the files to the same directory. To copy all the files except mp3s, we just have to type :
find . ! -name "*.mp3" -type f | xargs cp -t Destination/Folder
We hope that using this article you were able to learn more about the find and cp command, and you were able to copy all the files efficiently using the command line interface because copying like this with the GUI takes a lot of time as you will have to select individual files.