I want to find all files in dir1 having corresponding same file names in dir2, and replace them with the files from dir2.

For example:

dir1: first.txt second.txt
dir2: third.txt first.txt

So I want to remove from dir1 the old first.txt file and replace it with first.txt from dir2.

How to achieve this using Bash terminal?


Actually, there's a single command that does exactly what you're asking.

rsync -av --existing dir2/ dir1/

This will recursively copy the files from dir2 into dir1 only if the file already exists in dir1.

The -av options are the options you'll usually use for copying files using rsync.

The --existing option tells rsync to skip creating new files on receiver.

You must have the trailing slash on dir2/ on the command line because rsync behaves differently than most commands in the slash has a meaning to rsync.

rsync can also be used over the network similar to scp.

rsync can handle many other types of file synchronization, updating, and backup tasks.

  • Thanks, Can you please help with this sub question: How can I dlete fromdir1 all duplicate files? – michael Nov 3 '15 at 11:22
  • Please post another question and describe as clearly as possible what you want to accomplish with examples, like you did on this question. – RobertL Nov 3 '15 at 11:23

rsync can do this with the --existing option:

rsync -v --existing dir2/* dir1/

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.