How can i copy the contents of a directory located in multiple locations using find command and preserving directory structure?

Viewed 53

I have a folder named accdb under multiple directories all under one parent directory dist. I want to copy the contents of accdb for all directories while preserving the code structure

I succeeded in making the recursive folder structure with:

cd ~/dist; find . -name "accdb" -type d -exec mkdir -p -- ~/acc_trial/{} \; 

But i am failing to copy the contents of accdb. This command just makes the structure until directory accdb.

I tried

find . -name "accdb" -type d -exec mkdir -p -- ~/acc_trial/{} \ && cp -r {} ~/acc_trial/{} \;

I get an error:

find: missing argument to `-exec'

1 Answers

I don't know if this is possible using only a find expression, I'm pretty sure it is not. Besides you must consider that if you have one subfolder named accdb inside one accdb folder you'll probably get an error, that's why in the script that I've made I decided to use rsync:

#!/bin/bash
DEST='/home/corronx/provisional/destination_dir'
#Clean destination directory, PLEASE BE CAREFUL IT MUST BE A REMOVABLE DIRECTORY
rm -rf $DEST/*

FIND='test'
LOOK_PATH='/home/corronx/provisional'
FILES=($(find . -type d -name $FIND))


for ((i=0; i<${#FILES[@]};i++))
do
        #Remove first character .
        FILES[$i]=${FILES[$i]:1:${#FILES[$i]}}
        #Create directories in destination path
        mkdir -p $DEST${FILES[$i]}
        rsync -aHz --delete ${FILES[$i]:1:${#FILES[$i]}}/ $DEST${FILES[$i]}
        echo $i
done

Explanation

First of all I'd recommend using full paths in your script because an rm -rf expression inside an script is pretty dangerous (If you want comment that line and delete destination folder before running script).

DEST= Destination path.

FIND= Subfolder name that your are looking for.

LOOK_PATH= Path where you want to execute find

I create an array called FILES that contain all folders that returns find expression, after that I just create destination directories and run rsync to copy files, I've used rsync because I think it is better in case there is any subdirectory with the same name.

PLEASE BE CAREFUL WITH rm -rf expression, if DEST is not set you'll delete everything in your machine

Related