A Merii
A Merii

Reputation: 594

Copy files to another directory containing the same directory structure in bash

I have the following directory structure:

dir1
+-- _class1
|   +-- _i
|   +-- _ii
|   +-- _iii
|   +-- _...
+-- _class2
|   +-- _i
|   +-- _ii
|   +-- _iii
|   +-- _...
+-- _class3
|   +-- _i
|   +-- _ii
|   +-- _iii
|   +-- _...
+-- _...

Each class contains the exact same directories, and the directories contain png files.

What I want to do is copy the contents from dir1 to dir2 such that dir2 has the following format:

dir2
+-- _i
|
+-- _ii
|
+-- _iii
|
+-- _...

For example: dir2/i/*.png should contain all the files in dir1/class1/i/*.png, dir1/class2/i/*.png, dir1/class3/i/*.png, etc...

I have tried doing the following:

for dir in dir1/*/; do 
    cp -r dir1 dir2; 
done

But I get the following structure instead:

dir2
+-- _i
|
+-- _ii
|
+-- _iii
|
+-- _...
|
+-- _class2
|   +-- _i
|   +-- _ii
|   +-- _iii
|   +-- _...
+-- _class3
|   +-- _i
|   +-- _ii
|   +-- _iii
|   +-- _...
+-- _...
|   +-- _i
|   +-- _ii
|   +-- _iii
|   +-- _...

It seems to only work on the first directory and then it proceeds to create other directories instead of copying them into the already existing directory structure.

What's the best way to go about doing this in bash?

Upvotes: 1

Views: 2098

Answers (2)

Léa Gris
Léa Gris

Reputation: 19685

Just use:

cp -R dir1/*/*/ dir2/

I don't think you need to iterate the pattern with the shell. The cp command can do it.

Upvotes: 2

Barmar
Barmar

Reputation: 782785

The wildcard needs another level to match the i, ii, etc. directories.

for dir in dir1/*/*/; do
    cp -R "$dir" dir2
done

Upvotes: 2

Related Questions