skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search