Tuesday, September 6, 2022

[SOLVED] Copy only the files from the intersection of two directories over from directory 1 to directory 2

Issue

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?


Solution

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.



Answered By - oguz ismail
Answer Checked By - Pedro (WPSolving Volunteer)