【问题标题】:cp dir recursivly excluding 2 subdirscp dir 递归排除 2 个子目录
【发布时间】:2012-03-16 21:50:43
【问题描述】:

我有 1 个目录,其中包含 9 个子目录和 10 个文件。 子目录有下一级子目录和文件。

/home/directory/
/home/directory/subdirectory1
/home/directory/subdirectory2
...
/home/directory/subdirectory9
/home/directory/file1
...
/home/directory/file10

我想递归复制所有子目录和文件,不包括:

/home/directory/subdirectory5
/home/directory/subdirectory7

最好的方法是什么?

【问题讨论】:

标签: linux bash unix cp


【解决方案1】:

为什么不像这样使用cp 命令:

cp -r /home/directory/!(subdirectory5|subdirectory7) /destination

【讨论】:

  • 不能在 bash 中工作!输出是“bash: !: event not found”
  • 在这种情况下,您应该设置调用:shopt -s extglobmkdir destination。然后它会工作。
【解决方案2】:
rsync -avz --exclude subdirectory5 --exclude subdirectory7 /home/directory/ target-path

【讨论】:

  • rsync 是要走的路。忘记cp
【解决方案3】:

您可以使用tar--exclude 选项:

{ cd /home/directory; tar -c --exclude=subdirectory5 --exclude=subdirectory7 .; } | { cd _destination_ ; tar -x; }

【讨论】:

    【解决方案4】:

    使用rsync--exclude 更好

    【讨论】:

    • rsync 是一种更好的方法。
    【解决方案5】:

    也许find 命令会帮助你:

    $ find /home/directory -mindepth 1 -maxdepth 1 -name 'subdirectory[57]' -or -exec cp -r {} /path/to/dir \;
    

    【讨论】:

    • 这不会保留目录树结构,@kjohri 对 rsync 的回答要好得多
    • 这个命令甚至对我不起作用,它说 -exec 缺少一个参数
    【解决方案6】:

    Kev 的方式更好,但这也可以:

    find "/home/folder" -maxdepth 1 | sed -e "/^\/home\/folder$/d" -e "/^\/home\/folder\/subfolder5$/d" -e "/^\/home\/folder\/subfolder7$/d" -e "s/^/cp \-r /" -e  "s/$/ \/home\/target/" | cat
    

    解释:

    find "/home/folder" -maxdepth 1 |
    // get all files and dirs under /home/folder, pipe output
    
    sed -e "/^\/home\/folder$/d" 
    // have sed strip the path being searched, or the cp -r we prepend later will pickup the excluded dirs again.
    
    -e "/^\/home\/folder\/subfolder5$/d"
    // have sed strip subfolder5
    
    -e "/^\/home\/folder\/subfolder7$/d"
    // have sed strip subfolder7
    
    -e "s/^/cp \-r /"
    // have sed prepend "cp -r " to each line
    
    -e  "s/$/ \/home\/target/" | cat
    // have sed append targetdir to each line.
    

    输出:

    cp -r /home/folder/subfolder9 /home/target
    cp -r /home/folder/subfolder1 /home/target
    cp -r /home/folder/file10 /home/target
    cp -r /home/folder/subfolder2 /home/target
    cp -r /home/folder/file1 /home/target
    cp -r /home/folder/subfolder3 /home/target
    

    | cat更改为| sh以执行命令。

    你应该 Kev 的解决方案更好

    【讨论】:

    • +1 表示通过管道传输到 cat 或 sh 的过于复杂的 sed - 构建其他复杂脚本的最佳方式。在这种情况下,Kev 的正确答案 +1 :)
    【解决方案7】:

    我不知道使用cp 的好方法,但使用rsync--exclude 开关相当容易。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-26
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      • 2014-05-12
      • 2017-03-26
      相关资源
      最近更新 更多