Copy Folder Structure and Selected Files

When working on a project last year, I had to migrate and sets of derivative images and associated text files from an internal server to a development server. The project requirements included the retention of the existing folder structure of any folders that contained a few extensions but did not require all of the files contained in the folders. I knew I could use rsync but wanted to see if there were other commands that would achieve the same result.

Using the find command below from the origin directory, I was able to recursively find all folders that contained, the required files. For the example, I’ve only included .jpg and .txt but this could easily be extended. -iname is included to indicate that the extension should be case insensitive.

$ find . -iname *.jpg -or -iname *.txt 

The simple solution to migrating the files is a unix command on your mac.

$ cpio

CPIO is a utility that archives files and their existing structure.In copy-pass mode, cpio copies files and their folder structure without archiving. The options are described below.

p indicates pass through mode

d makes directories

m preserves modification time

u replaces files unconditionally

Below is the combined find and cpio command which pipes the result of the find to cpio.

$ find . -iname *.jpg -or -iname *.txt | cpio -pdmu /newServer/newFolder/

Simple, fast one line bash awesomeness.

Check this page for more info about cpio.

Leave a Reply

Your email address will not be published. Required fields are marked *