简体   繁体   中英

Bash - How to loop through sub directories and copy in a file

I'm new to coding in bash.

I'm trying to create something which will loop through all subdirectories, and within each one it should copy a file to that directory.

So for example, if I have the following directories

/dir1/  
/dir2/  
/dir3/  
...  
...  
/dirX/

And a file fileToCopy.txt

Then I want to run something which will open every single /dirX file and put fileToCopy.txt in that directory. Leaving me with:

/dir1/fileToCopy.txt
/dir2/fileToCopy.txt
/dir3/fileToCopy.txt
...
...
/dirX/fileToCopy.txt

I would like to do this in a loop, as then I am going to try to modify this loop to add some more steps, as ultimately the .txt file is actually a .java file, I am wanting to copy it into each directory, compile it (with the other classes in there), and run it to gather the output.

Thanks.

for i in dir1, dir2, dir3, .., dirN
    do
        cp /home/user1068470/fileToCopy.txt $i
    done

Alternatively, you can use the following code.

for i in *
    do                 # Line breaks are important
        if [ -d $i ]   # Spaces are important
            then
                cp fileToCopy.txt $i
        fi
    done

查找当前目录(。)下的所有目录并将文件复制到其中:

find . -type d -exec cp fileToCopy.txt '{}' \;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM