How can I search for files in all sub-directories using the shell and then copy those files?

How can I find just the *.mp3 files with a recursive command like ls -R *.mp3 in a directory that contains several sub-directories and at the end copy these files in a directory that I choose.

Thanks for your support.


The command is:

find /path/to/directory -name "*.mp3" -exec cp {} /some/other/dir/ \;

Alternative:

find /path/to/dir/ -name '*.mp3' | xargs cp -t /target/

Example:

alex@MaD-pc:~/test$ ls
1  2  3
alex@MaD-pc:~/test$ ls 1 2 3
1:
1.txt  2.mp3  3.txt

2:
4.txt  5.mp3  6.txt

3:
alex@MaD-pc:~/test$ find . -name "*.mp3" -exec cp {} 3/ \;
alex@MaD-pc:~/test$ ls 3
2.mp3  5.mp3

For more information:

man find

There is also another way to do it which I think will suit your purpose perfectly. You can combine find with a while loop and not even need to use either of exec or xargs at all. If, for example you wanted to copy your mp3s from your download folder to your music folder, you would use the following script, which I have used many times.

You can modify it how you want by changing the directories that find searches and places the resulting files in; if no directory is stated, find will search the entire home folder. You can also change cp to mv or other commands. It is pretty fast, as I have just tested it with 3945 .jpg files! Copy it into a text editor, save it and then make it executable by running chmod +x myscript.

#!/bin/bash
# a script to recursively find and copy files to a desired location
find ~/Downloads -type f -iname '*.mp3' -print0 |
while IFS= read -r -d '' f; 
do cp -- "$f" ~/Music ;
done

At this noted Bash wiki it is shown how useful it is to combine the while loop and read commands to process the output of the find command; and the way I have done it makes sure that the script will not break if it comes across file names with spaces or other unexpected or special characters.

For more general information on the find command, enter in the terminal man find or see the Ubuntu manpages online. For a great introduction to the use of find, see this article as well.