26 de junio de 2014

How to merge two folders in Mac OS X or Linux


Short answer


Using the command line (Terminal):
cp -r -n ~/Desktop/src/* ~/Desktop/destination/
The command above adds the src content and the subdirectories to the destination without overwriting the content already present in the destination.

Long answer

Even if the content overlaps, you can still use cp to do it. Assume that you have two folders on your desktop: the src and the destination folders and you want to merge src into destination:
enter image description here
To merge, just do:
cp -r ~/Desktop/src/* ~/Desktop/destination/
NOTE When you use this, the content in src overwrites the content in the destination folder and adds the extra stuff that are missing in the destination. It shouldn't matter if you just want to add the missing files from src into destination.
ALSO it doesn't matter how many subdirectories are there, it will just go through each folder recursively and it will overwrite the content and will add the stuff that is missing in the destination folder.
BUT
PITFALL If you have huge files (like video files), you don't want to wait until everything is overwritten, it adds a lot of overhead.
PITFALL SOLUTION: Instead, you can use the -n flag to skip the overwriting:
cp -r -n ~/Desktop/src/* ~/Desktop/destination/
This is the description of the -n flag from the man page:
man cp
 -n    Do not overwrite an existing file.  (The -n option overrides any
       previous -f or -i options.)
Further Reading
  1. http://stackoverflow.com/questions/5088332/overhead-of-a-flag-in-cp-command
Source:

1 comentario:

Unknown dijo...

You can also use option -i instead of -n to choose if you want to overwrite each file