Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I merge one directory into another using Bash?

I'm looking for shell script that merge files from one directory into another.

Sample:

html/   a/     b.html   index.html  html_new/   a/     b2.html     b.html 

Usage:

./mergedirs.sh html html_new 

Result:

html/   a/     b.html     b2.html   index.html 

html/a/b.html was replaced by html_new/a/b.html
html/a/b2.html was copied from html_new/a/b2.html
html/index.html was kept untouched

like image 253
NVI Avatar asked Dec 31 '10 20:12

NVI


People also ask

How do I merge two directories in Linux?

cp is one of the simplest commands to help you merge folders & directories in Linux. Here is the syntax to copy multiple folders into a single one.

How do I copy a folder to another directory in bash?

Copy a Directory and Its Contents ( cp -r ) Similarly, you can copy an entire directory to another directory using cp -r followed by the directory name that you want to copy and the name of the directory to where you want to copy the directory (e.g. cp -r directory-name-1 directory-name-2 ).

How do I merge folders?

If you are just looking to merge the contents of two directories into a single folder, then the default method is the best approach. Just open File Explorer, rename one of the folders to the same name, and copy-paste over the other, letting Windows handle the merger.


2 Answers

cp -RT source/ destination/ 

All files and directories in source will end up in destination. For example, source/file1 will be copied to destination/file1.

The -T flag stops source/file1 from being copied to destination/source/file1 instead. (Unfortunately, cp on macOS does not support the -T flag.)

like image 115
Flimm Avatar answered Sep 21 '22 05:09

Flimm


You probably just want cp -R $1/* $2/ — that's a recursive copy.

(If there might be hidden files (those whose names begin with a dot), you should prefix that command with shopt -s dotglob; to be sure they get matched.)

like image 43
Luke Maurer Avatar answered Sep 22 '22 05:09

Luke Maurer