0

I want to copy one file into many directory. My path structure is like above.

folder1-> anotherfolder -> **here I want to copy my file**
folder2-> anotherfolder -> **here I want to copy my file**
folder3-> anotherfolder -> **here I want to copy my file**
folder4-> anotherfolder -> **here I want to copy my file**

folder1,2,3,4 is in the same directory. But the names are the folders are not sequential.

I can get the name of folders with this code but after that I don't know how can I get into the folders and copy my file.

    for d in */ ; do
     echo "$d"
    done

This code gives me the folders name in directory. After this step how can I get into folders and copy my file?

2 Answers 2

1

First try (has limitations)

for d in $(find . -maxdepth 2 -type d | grep "/.*/"); do
    cp file "$d"
done

LIMITATIONS:

  • No spaces/slashes/glob characters in the dir-names

Second try (cleaner, thanks to gniourf_gniourf)

find . -maxdepth 2 -path './*/*' -type d -exec cp file {} \;
Sign up to request clarification or add additional context in comments.

9 Comments

I've edited the solution to catch only paths like ./folderA/folderB/
It copied but the file name changed into anotherfolder. My actual file name is test.java
Please, no! this is broken if directory name contains spaces or other funny characters (glob characters, etc.) Your use of grep also looks wrong.
I've added the Limitations section. Anyone wanting to come with a generic solution is welcome!
Since you're relying on -maxdepth, I can assume GNU find or similar that has the -path predicate: find . -path './*/anotherfolder' -type d -exec cp file {} \;.
|
1

Seems like you want to do something like this:

for d in */; do
    cp file "$d"/anotherfolder
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.