使用终端将内容/文件复制到目录中的所有子目录

22l*_*nly 21 command-line cp

我想将文件复制到文件夹中的所有子文件夹。如何使用命令行执行此操作?

Yet*_*ser 35

如何将文件放在所有子文件夹中的当前工作目录中(可能还有它们的子文件夹,具体取决于您想要做什么)

这会将文件放在所有子文件夹中,但不会放在它们的子文件夹中:

for d in */; do cp water.txt "$d"; done
Run Code Online (Sandbox Code Playgroud)

这会将文件water.txt(将 water.txt 的所有实例更改为您要复制的文件名)放在所有子文件夹及其子文件夹中

for i in ./* # iterate over all files in current dir
do
    if [ -d "$i" ] # if it's a directory
    then
        cp water.txt "$i" # copy water.txt into it
    fi
done
Run Code Online (Sandbox Code Playgroud)

来自这个 linuxquestions 线程的信息


ort*_*ang 17

你可以使用那个单线:

find <target-dir> -type d -exec cp <the file> {} \;

将深度限制为 1 -> 仅直接目录

find <target-dir> -type d -maxdepth 1 -exec cp <the file> {} \;

  • 这会递归地执行所有子目录,而不仅仅是直接子目录 (2认同)
  • @Anake 更新了我的答案 (2认同)