Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy all files with a certain extension from all subdirectories

Tags:

bash

unix

cp

Under unix, I want to copy all files with a certain extension (all excel files) from all subdirectories to another directory. I have the following command:

cp --parents `find -name \*.xls*` /target_directory/

The problems with this command are:

  • It copies the directory structure as well, and I only want the files (so all files should end up in /target_directory/)

  • It does not copy files with spaces in the filenames (which are quite a few)

Any solutions for these problems?

like image 341
Abdel Avatar asked Oct 18 '22 18:10

Abdel


People also ask

How do I copy all file extensions in Linux?

Copy Files with Specific File Extensions 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.

How do I search for all files with specific extensions?

For finding a specific file type, simply use the 'type:' command, followed by the file extension. For example, you can find . docx files by searching 'type: . docx'.

What command do you use to copy files from all subdirectories to another directory?

To copy a directory with all subdirectories and files, use the cp command.


1 Answers

--parents is copying the directory structure, so you should get rid of that.

The way you've written this, the find executes, and the output is put onto the command line such that cp can't distinguish between the spaces separating the filenames, and the spaces within the filename. It's better to do something like

$ find . -name \*.xls -exec cp {} newDir \;

in which cp is executed for each filename that find finds, and passed the filename correctly. Here's more info on this technique.

Instead of all the above, you could use zsh and simply type

$ cp **/*.xls target_directory

zsh can expand wildcards to include subdirectories and makes this sort of thing very easy.

like image 269
Brian Agnew Avatar answered Oct 20 '22 06:10

Brian Agnew