Recursively copy only images and preserve path

cpfilesystemsfindrecursive

I'm working on a website migration. I have a scrape of the site, with all the files and directory structure as you would see them in the URL. I want to pull all images, maintaining the directory structure, and copy them into a new place.

For instance, if I have

/content1/index.php
/content1/page2.php
/content1/images/image1.jpg
/content1/images/image2.jpg
/content1/background/spacer.gif
/content1/background/background.gif
/content2/index.php
/content2/images/image3.jpg
/content2/background/spacer.gif
/content2/background/background.gif

Then I want

/content1/images/image1.jpg
/content1/images/image2.jpg
/content1/background/spacer.gif
/content1/background/background.gif
/content2/images/image3.jpg
/content2/background/spacer.gif
/content2/background/background.gif

I can use the find command to get a list of only image files, but I don't know how to manipulate each file while preserving the directory path to it.

I could make a copy of the entire directory, and then recursively delete any non-image file, but now that I have set this problem before myself, I figure its worthwhile to know how to do it, in case I really do need to do it this way later.

Best Answer

Try this command (find and cp with --parent option):

find /source -regextype posix-extended -regex '.*(gif|jpg)' \
    -exec cp --parents {} /dest \; -print
Related Question