How to find certain files and copy them with their directories to a directory?

We are trying to find all files in a directory, that contains multiple sub-directories for the file type ".png" and ".jpg". We are using:

find /otrs_attachment_files/2013/10/15/ -type f \( -name "*.png" -o -name "*.jpg" \) -exec cp -ar {} /root/otrs_test_filebackup \;

Open in new window

but it doesn't retain each files' directory.

What's the proper command?
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Add --parents to the cp command, like this:

find /otrs_attachment_files/2013/10/15/ -type f \( -name "*.png" -o -name "*.jpg" \) -exec cp -ar --parents {} /root/otrs_test_filebackup \;

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Would it be easier to use rsync?

rsync -am --include='*.png' --include='*.jpg' --include='*/' --exclude='*'  /root/otrs_test_filebackup
if you don't want / can't use rsync or your version of cp does not handle --parents

find ... | cpio -p TARGETDIR

if you don't have cpio, many archieving tools including tar and pax (likely available) can be used, but that would actually create a temorary archieve with a possibly large performance hit

cd TARGETDIR ; find ... | tar -c -f- | tar -x -f-

some versions of xargs can replace tokens several times ( and you can add -P for parallel processing ) but this spawns one command per file

find ... | xargs -J% cp % TARGETDIR/%

likewise in shell scripting (yes the double-double quotes work)

find ... | while read path
do   mkdir -p "`dirname "TARGETDIR/$path"`"
        cp "$path" "TARGETDIR/$path"
I just noticed that I forgot the source directory in my arguments.  Here's the corrected command.
rsync -am --include='*.png' --include='*.jpg' --include='*/' --exclude='*'  /otrs_attachment_files/2013/10/15/ /root/otrs_test_filebackup

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.