Using find to copy specific files on Linux
I was faced with a weird copy command I wanted to do today; so I thought I would share.
How do you copy files in a directory tree to another directory?
I wanted to copy all of the mp3 files in a directory tree over to one specific target directory.
Initially I thought the command
cp -r *.mp3 /target/directory/
would work, but even though it specifies the –recursive option, it does not iterate the subdirectory looking for the mp3 files.
So I resorted to my every faithful companion: find -exec. It seems like this is one of the most useful tools in Linux. In this case, here is the command line I used:
find . -type f -name ‘*.mp3’ -exec cp {} /targetdirectory/ \;
I think you’ve got a point there Brian, find -exec and xargs are probably second only to bash for loops with command substutions for the most useful tools I have for day to day ops.