How to copy all files recursively excluding folders into one destination folder?

3

3

I have several folders like /music/1/a.mp3 and /music/2/b.mp3

All of the file names themselves are guaranteed to be different.

Is there a way, probably using the Terminal, to copy these files to /musicTemp/ excluding the folders?

In other words, the result of the two examples above should be:

/music/1/a.mp3
/music/2/b.mp3

into:

/musicTemp/a.mp3
/musicTemp/b.mp3

samiles

Posted 2013-03-07T21:50:04.070

Reputation: 131

2Does Finder provide an option to search for files recursively? If yes, search, select all, and drag to your destination. I know that's a good option on other OSes. – Ben Voigt – 2013-03-07T21:51:35.127

1That's so obvious I just facepalmed. All files are .m4a and Finder lets me limit to just /music/. Thanks!!! – samiles – 2013-03-07T21:52:56.343

1Just to add an alternative: find /music -name "*.mp3" -type file -exec mv {} /destination_dir \; – Hennes – 2013-03-07T21:54:56.930

2@Hennes: cp not mv. Otherwise that should work. – Ben Voigt – 2013-03-07T21:59:46.057

Answers

5

The find command will find all files of the specified pattern (-name), in this case a specific file type: *.mp3. -exec makes all following arguments to find to be taken as arguments to the command until an argument consisting of ; is encountered (at the end, with literal escape to prevent expansion by the shell). In this case, the command we wish to execute is a file copy (cp) on files that match pattern ({}) and copy those files to /destination_dir. This command should do the trick:

find /music -name "*.mp3" -type file -exec cp {} /destination_dir \;

Dan

Posted 2013-03-07T21:50:04.070

Reputation: 803

3

If you have installed Bash 4, you could add shopt -s globstar to .bash_profile and run this:

cp /music/**/*.mp3 /musicTemp/

Lri

Posted 2013-03-07T21:50:04.070

Reputation: 34 501

Not sure what shopt.. is necessary for as this works without mods, also with mv.. Thanks anyhow the ** is new to me :) – geotheory – 2015-03-26T15:41:17.507