Skip to content
Advertisement

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?

Advertisement

Answer

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

for dir in dir1/*/*/; do
    cp -R "$dir" dir2
done
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement