【问题标题】:Copy file into multiple directories - Unix将文件复制到多个目录 - Unix
【发布时间】:2015-08-21 08:39:11
【问题描述】:

我想将一个文件复制到多个目录中。我的路径结构如上。

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**

文件夹 1,2,3,4 位于同一目录中。但是名称是文件夹不是顺序的。

我可以使用此代码获取文件夹的名称,但之后我不知道如何进入文件夹并复制我的文件。

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

此代码为我提供了目录中的文件夹名称。完成此步骤后,如何进入文件夹并复制我的文件?

【问题讨论】:

    标签: linux bash unix directory directory-structure


    【解决方案1】:

    第一次尝试(有限制)

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

    限制:

    • 目录名称中没有空格/斜杠/全局字符

    第二次尝试(更干净,感谢 gniourf_gniourf)

    find . -maxdepth 2 -path './*/*' -type d -exec cp file {} \;
    

    【讨论】:

    • 我已编辑解决方案以仅捕获 ./folderA/folderB/ 之类的路径
    • 它已复制但文件名已更改为另一个文件夹。我的实际文件名是 test.java
    • 请不要!如果目录名称包含空格或其他有趣的字符(glob 字符等),这将被破坏。您对 grep 的使用看起来也有问题。
    • 我添加了限制部分。欢迎任何想要提供通用解决方案的人!
    • 由于您依赖-maxdepth,我可以假设GNU find 或具有-path 谓词的类似物:find . -path './*/anotherfolder' -type d -exec cp file {} \;
    【解决方案2】:

    好像你想做这样的事情:

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

    【讨论】:

      猜你喜欢
      • 2012-09-29
      • 1970-01-01
      • 1970-01-01
      • 2017-11-11
      • 2015-10-15
      • 1970-01-01
      • 1970-01-01
      • 2019-11-14
      • 1970-01-01
      相关资源
      最近更新 更多