Linux find command: find and copy files

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:

  1. 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.
  2. If there are duplicate file names, some of the files will be lost.

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.

Post new comment

The content of this field is kept private and will not be shown publicly.