Bash - 如何遍历子目录并复制到文件中

The*_*son 2 unix bash copy

我是bash编码的新手.

我正在尝试创建一些将遍历所有子目录的东西,并且在每个子目录中它应该将文件复制到该目录.

例如,如果我有以下目录

/dir1/  
/dir2/  
/dir3/  
...  
...  
/dirX/
Run Code Online (Sandbox Code Playgroud)

还有一个档案 fileToCopy.txt

然后我想运行一些会打开每个/dirX文件并放入fileToCopy.txt该目录的东西.离开我:

/dir1/fileToCopy.txt
/dir2/fileToCopy.txt
/dir3/fileToCopy.txt
...
...
/dirX/fileToCopy.txt
Run Code Online (Sandbox Code Playgroud)

我想在循环中执行此操作,因为我将尝试修改此循环以添加更多步骤,因为最终.txt文件实际上是.java文件,我想将其复制到每个目录中,编译它(与其中的其他类),并运行它来收集输出.

谢谢.

ase*_*ovm 6

for i in dir1, dir2, dir3, .., dirN
    do
        cp /home/user1068470/fileToCopy.txt $i
    done
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用以下代码.

for i in *
    do                 # Line breaks are important
        if [ -d $i ]   # Spaces are important
            then
                cp fileToCopy.txt $i
        fi
    done
Run Code Online (Sandbox Code Playgroud)


Gur*_*uru 6

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

find . -type d -exec cp fileToCopy.txt '{}' \;
Run Code Online (Sandbox Code Playgroud)