MacOS – Copy a folder(and its internal structure), but only include specific files

findermacosmp3

I have a folder(with subfolders and further subfolders) that the final folder has many different file types. These file types include images(.png/.jpeg), videos(.mov), and text files(.txt). But I would like to copy the entire folder(with the internal structure) and only include .mp3's. Does anyone have any ideas how do do this. (please do not say manually because there are 100+ folders and the folder itself is 60GB, so don't tell me to copy the whole folder) Preferably, I would like if someone was able to give me a solution where I can outright move the .mp3's(while preserving the folder structure)

Best Answer

The following two commands, used in a Terminal, can accomplish what you've asked, the first creating a destination hierarchical directory structure containing the *.mp3 files and the second command deleting the *.mp3 files from the source hierarchical directory structure.

Note: Make sure you have proper backups before using the second command as a mistype can be fatal.

Open Terminal.

By default Terminal opens to one's Home Directory so I'll use it as the example starting point and the Music directory as the source hierarchical directory structure.

This first command will make a copy of the Music hierarchical directory structure containing only *.mp3 files in the destination directory. In other words after the first command is run there will be a destination directory containing that same hierarchical directory structure starting at Music within the destination directory that contains only *.mp3 files and only the directories from the source that contain *.mp3 files. If a given source directory does not contain a *.mp3 file then that directory is not created in the destination directory hierarchical structure.

Note: Full command line extends out of view without horizontal scrolling.

find ./Music -name "*.mp3" -type f -print0 | xargs -0 -I '{}' /usr/bin/rsync -avR "{}" "./mp3 files only/"

Note: Full command shown on two lines for clarity:

find ./Music -name "*.mp3" -type f -print0 | \
xargs -0 -I '{}' /usr/bin/rsync -avR "{}" "./mp3 files only/"

When the above command finishes there will be a directory in my Home Directory named "mp3 files only" and within that directory there will be a Music hierarchical directory structure containing only *.mp3 files. Note: If the destination directory does not exist it will automatically be created.

Now that the *.mp3 files have been copied from the source Music hierarchical directory structure to the "mp3 files only" directory the *.mp3 files can be removed from the source Music hierarchical directory structure with the following command.

find  ./Music/ -name "*.mp3" -delete

That's it, the *.mp3 files along with their hierarchical directory structure have been copied to a new location and the *.mp3 files deleted from the source.