I have two directories dirOrig and dirDest in different remote servers. Both of them have numerous subdirectories at various depths. I now need to copy a specific file or extension -- say file1.txt recursively from dirOrig to dirDest. But, I need to copy the file only if the subdirectory is already present in dirDest.

For example, I can systematically copy only a specific file from source to destination using rsync using

rsync -zarv  --prune-empty-dirs --include "*/"  --include="file1.txt" --exclude="*" "dirOrig" "dirDest"

But how to restrict this copy only to the subdirectories present in the destination (dirDest)

1 Answer 1


I dont know of a single command, but the hack that I came up with is as follows.

  1. Use rsync to copy the dirOrig from server1 to server2

    rsync -zarv --prune-empty-dirs --include "*/" \ --include="file1.txt" --exclude="*" "server1:dirOrig" \ "server2:dirOrig"

  2. Delete the subdirectories in the copied dirOrig that are not present in dirDest using comm

    comm -23 <( cd server2:dirOrig && find -mindepth 1 -type d | sort ) \ <( cd server2:dirDest && find -mindepth 1 -type d | sort ) \ | ( cd server2:dirOrig && xargs rm -rf )

  3. Finally rsync the dirDest with dirOrig based on checksum and delete all files in dirOrig not present in dirDest except for file1.txt

    rsync -acv --exclude=file1.txt --delete \ server2:dirDest server2:dirOrig

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.