Unix: How to merge two directories

17

2

Say I have two folders with various content, foo and bar. How can I merge bar into foo so that:

  • Files in foo that are not in bar are untouched.
  • Files in bar that are not in foo are now in foo.
  • Files in foo that are also in bar have been replaced by the files from bar.

Svish

Posted 2011-02-07T11:54:20.870

Reputation: 27 731

Answers

25

If I'm reading your requirements correctly, there's no files that go from foo to bar. It looks like you can just copy the contents of bar to foo, letting it overwrite files as necessary (its default behavior).

$ cp -R /path/to/bar/* /path/to/foo

coneslayer

Posted 2011-02-07T11:54:20.870

Reputation: 7 494

1Note: it will omit hidden files/directories in bar (i.e. with names starting with a dot – .) because of how shell globbing works. – Kamil Maciorowski – 2017-06-15T17:10:35.953

Yeah, what I was uncertain about was the recursiveness and how to not end up with just having bar inside foo as foo/bar. But this seems to be what I want :) – Svish – 2011-02-07T12:57:37.570

1Right, if you just did cp -R /path/to/bar /path/to/foo it would create a directory bar inside foo. Subtle point. – coneslayer – 2011-02-07T13:20:48.750

9

I had a very similar need: merge bar into foo but files which are in bar should not overwrite matching files in foo. In this case:

$ cp -R -n /path/to/bar/* /path/to/foo/

Joel Aufrecht

Posted 2011-02-07T11:54:20.870

Reputation: 193

1

Try this :

$ cp -r-u-v /path/to/foo/* /path/to/bar/

From man cp
-u, --update copy only when the SOURCE file is newer than the destination file or when the destination file is missing
-R, -r, --recursive copy directories recursively

drew7721

Posted 2011-02-07T11:54:20.870

Reputation: 824

1Two people have already suggested the cp command and so your answer seems superfluous. Taking a few minutes to explain how the arguments you've selected do a better job than the other suggestions will help make your answer more helpful. – music2myear – 2017-06-15T17:21:33.890

1The -u flag updates only if the file in the source is newer that the one in the destination. See : man cp -> -u, --update : copy only when the SOURCE file is newer than the destination file or when the destination file is missing – drew7721 – 2017-06-16T17:52:58.413

Add that information to the question (use Edit right below your post) so that people can see that helpful information in the answer itself. – music2myear – 2017-06-16T17:55:10.397