Merging nested directories by name

Refresh

March 2019

Views

56 time

1

I am looking for a way to merge the contents of two nested directories if their names match. The new combined folder needs to be placed in a new directory. If there is not a folder in directory 2 that matches the name of the folder in directory 1, the folder from directory 1 must still be copied into the new master directory.

For example, let's say I have a directory structure as follows:

* dir1

  * foo

     * file1

  * bar

     * file2

  * extra

     * file3

* dir2

  * foo

     * file4

  * bar

     * file5

I would like the output to be:

* newdir

  * foo

     * file1

     * file4

  * bar

     * file2

     * file5

  * extra

     * file3

Thank you in advance for your help!

1 answers

2

There are two ways. ditto is for OS X and gets the job done in less commands. cp -a will work in any bash shell.

Here is my test folder, modeled after your example.

.
├── dir1
│   ├── bar
│   │   └── file2
│   ├── extra
│   │   └── file3
│   └── foo
│       └── file1
└── dir2
    ├── bar
    │   └── file5
    └── foo
        └── file4

Then, run one of the following (depending on your platform):

OSX:

$ ditto dir1/ dir2/ newdir/

LINUX:

$ cp -a dir1/ newdir/
$ cp -a dir2/ newdir/

Resulting directory:

.
├── dir1
│   ├── bar
│   │   └── file2
│   ├── extra
│   │   └── file3
│   └── foo
│       └── file1
├── dir2
│   ├── bar
│   │   └── file5
│   └── foo
│       └── file4
└── newdir
    ├── bar
    │   ├── file2
    │   └── file5
    ├── extra
    │   └── file3
    └── foo
        ├── file1
        └── file4

Source (ditto): https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/ditto.1.html