Linux find/copy FAQ: How can I use the find
command to find many files and copy them all to a directory?
I ran into a situation this morning where I needed to use the Linux find command to (a) find all the MP3 files beneath my current directory and (b) copy them to another directory. In this case I didn't want to do a cp -r
command or tar command to preserve the directory structure; instead, I wanted all of the files to end up in the same directory (so I could easily import them into iTunes).
In short, here's the find
command I used to find and copy all of those files:
find . -type f -name "*.mp3" -exec cp {} /tmp/MusicFiles \;
If you're familiar with the find
command and have used the -exec
option before, the only thing hard about this command is knowing where to put the curly braces and the \;
in the command.
A few points:
- In this example, all the MP3 files beneath the current directory are copied into the target directory (/tmp/MusicFiles). Again, this isn't a
cp -r
command; all of these files will end up in one folder. - As a result, if there are duplicate file names, some of the files will be lost.
- If you don’t want to overwrite existing files, use the
cp -n
command, like this:
find . -type f -name "*.mp3" -exec cp -n {} /tmp/MusicFiles \;
The -n
option of the cp
command means “no clobber,” and you can also type that as cp --no-clobber
on some systems, such as Linux. (The -n option appears to work on MacOS systems, but --no-clobber
does not.) Be sure to test this command before using it on something important; I haven’t tested it yet, I just read the man page for the cp
command.)
If you ever need to use the Linux find
command to find a large collection of files and copy them to another location, I hope this has been helpful.
Another example: Find and move
Here’s another example of a “find and copy” command I just used, though in this case it was a “find and move” command. In this case I had a bunch of files (with unique names) in subdirectories, and used this command to copy them all to the current directory:
find . -type f -exec mv {} . \;
As before, this is a dangerous command, so be careful. With this command, if you have duplicate filenames, you will definitely lose data during the move operations.
Comments
Is there any way to not overwrite dup names?
Serious newb here, but wondering if you could "-exec" a command to append a file date (or rename based on files's creation date and time) and then copy or move it to your 'collection' directory? Or some other way to rename dups so they don't overwrite?
I used a counter
Yes, in the example on this page I show how I do that using a shell script and a counter. You can modify that to get and use the file’s timestamp if you’d prefer that over a counter.