【问题标题】:How can I recursively copy the directory contents and exclude the source directory itself?如何递归复制目录内容并排除源目录本身?
【发布时间】:2013-10-15 21:09:47
【问题描述】:

使用 FileUtils cp_r 通常是我复制目录的方式,但我似乎无法排除基本目录。这就是我想要的工作,但它没有:

FileUtils.cp_r "#{source_path}\\**", target_path, :verbose => true

source_path 有我想递归复制的子目录。我只是不想要实际的source_path 目录,只想要它下面的所有内容。

我尝试使用Dir.glob,但无法正确使用。

这是一个 Windows 副本,我知道我可以使用 xcopy,但想知道如何在 Ruby 中进行操作。

【问题讨论】:

    标签: ruby copy fileutils


    【解决方案1】:

    您想使用source_path/. 而不是source_path/**,如documentation 的最后一个示例中所述

    ➜  fileutils  ls
    cp_files.rb dst         source
    ➜  fileutils  tree source 
    source
    ├── a.txt
    ├── b.txt
    ├── c.txt
    └── deep
        └── d.txt
    
    1 directory, 4 files
    ➜  fileutils  tree dst 
    dst
    
    0 directories, 0 files
    ➜  fileutils  cat cp_files.rb 
    require 'fileutils'
    FileUtils.cp_r "source/.", 'dst', :verbose => true
    ➜  fileutils  ruby cp_files.rb 
    cp -r source/. dst
    ➜  fileutils  tree dst
    dst
    ├── a.txt
    ├── b.txt
    ├── c.txt
    └── deep
        └── d.txt
    
    1 directory, 4 files
    

    这就是 cp_files.rb 的样子:

    require 'fileutils'
    FileUtils.cp_r "source/.", 'dst', :verbose => true
    

    【讨论】:

    • 如果您有想要递归复制的空目录,最好添加一个.keep 文件,这样递归复制就不会忽略它们
    【解决方案2】:

    请使用FileUtils.copy_entry 实用程序。提供源和目标的完整路径。它将递归地从源复制到目标,不包括源父目录。此方法保留文件类型,c.f.符号链接、目录……(FIFO、设备文件等暂不支持)

    示例用法:

    src = "/path/to/source/dir"
    dest = "/path/to/destination/dir"
    preserve = false
    dereference_root = false
    remove_destination = false
    
    FileUtils.copy_entry(src, dest, preserve, dereference_root, remove_destination)
    

    srcdest 都必须是路径名。 src 必须存在,dest 不能存在。

    如果preserve 为真,此方法会保留所有者、组、权限和修改时间。可选使用。

    如果dereference_root 为真,则此方法取消引用树根。可选使用。

    如果 remove_destination 为 true,此方法会在复制前删除每个目标文件。可选使用。

    欲了解更多信息,check out the documentation

    【讨论】:

    • 此答案不回答 OP 的问题
    猜你喜欢
    • 2013-12-16
    • 1970-01-01
    • 2011-03-21
    • 2018-03-01
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多