Avatar of meade470
meade470
 asked on

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?
LinuxUnix OSShell Scripting

Avatar of undefined
Last Comment
serialband

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
ThomasMcA2

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
serialband

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
skullnobrains

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"
done
serialband

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

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck