Copy all files with a specific extension from all subdirectories

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

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

Problems with this command:

  • It also copies the directory structure, and I only need the files (so all files should be in / target _directory /)

  • It does not copy files with spaces to file names (of which there are quite a lot)

Any solutions for these tasks?

+86
unix bash cp
Mar 25 '13 at 14:09
source share
5 answers

--parents copies the directory structure, so you should get rid of this.

As you wrote this, find is executed, and the output is placed on the command line in such a way that cp cannot distinguish between spaces separating file names and spaces inside the file name. Better do something like

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

in which cp is executed for each file name that find finds, and passed the file name correctly. Here is more about this technique.

Instead, you can use zsh and just type

 $ cp **/*.xls target_directory 

zsh can extend wildcards to include subdirectories, and makes such things very easy.

+136
Mar 25 '13 at 14:10
source share

From all of the above, I came up with this version. This version also works for me in the Mac recovery terminal.

 find ./ -name '*.xsl' -exec cp -prv '{}' '/path/to/targetDir/' ';' 

It will look in the current directory and recursively in all subdirectories for files with the xsl extension. It will copy them all to the target directory.

Flags

cp:

  • p - save file attributes
  • r - recursive
  • v - verbose (shows you what copying is)
+24
May 03 '16 at 18:48
source share

I had a similar problem. I solved this using:

 find dir_name '*.mp3' -exec cp -vuni '{}' "../dest_dir" ";" 

'{}' and ";" makes a copy of each file.

+8
Jan 18 '15 at 22:47
source share

I also had to do it myself. I did this through the -parents argument to cp:

 find SOURCEPATH -name filename*.txt -exec cp --parents {} DESTPATH \; 
+3
Dec 03 '17 at 22:56 on
source share
 find [SOURCEPATH] -type f -name '[PATTERN]' | while read P; do cp --parents "$P" [DEST]; done 

You can remove --parents, but there is a risk of collision if multiple files have the same name.

0
May 13 '19 at 2:11
source share



All Articles