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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13008382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:36:26  来源:igfitidea点击:

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

bashunixcopy

提问by ThePerson

I'm new to coding in bash.

我是 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

还有一个文件 fileToCopy.txt

Then I want to run something which will open every single /dirXfile and put fileToCopy.txtin that directory. Leaving me with:

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

/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.

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

Thanks.

谢谢。

回答by asenovm

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

回答by Guru

Finds all directory under the current directory (.) and copies the file into them:

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

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