Home > Net >  Copy only the files from the intersection of two directories over from directory 1 to directory 2
Copy only the files from the intersection of two directories over from directory 1 to directory 2

Time:08-20

Suppose I have:

dir_1
- file_a
- subdir_0
  - file_b
- file_c
dir_2
- file_a
- subdir_0
  - file_b

I want to copy over every file that exists in both directories to dir_2. In the above example, this would mean file_a and subdir_0/file_b.

What's the easiest way to accomplish this in bash?

CodePudding user response:

Using find and a shell loop:

find dir_2 -type f -exec sh -c '
for dst; do
  src=dir_1${dst#dir_2}
  if test -f "$src"; then
    echo cp "$src" "$dst"
  fi
done' sh {}  

Remove echo to actually copy the files.

CodePudding user response:

One find/while/read idea:

while read -r tgt
do
    src="${tgt//dir_2/dir_1}"
    [[ -f "${src}" ]] && echo cp "${src}" "${tgt}"     # if satisfied with output then remove the 'echo'
done < <(find dir_2 -type f)

This generates:

cp dir_1/file_a dir_2/file_a
cp dir_1/subdir_0/file_b dir_2/subdir_0/file_b
  • Related