ruby 将一个目录的内容复制到另一个目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11436680/
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-06 05:17:15  来源:igfitidea点击:

Copy contents of one directory to another

ruby

提问by Phrogz

Using Ruby, how can I copy the contentsof one directory to another? For example, given (non-empty) directories A and B:

使用 Ruby,如何将一个目录的内容复制到另一个目录?例如,给定(非空)目录 A 和 B:

A/
  bar
  foo
B/
  jam
  jim

I want to copy everything from A into B, resulting in:

我想将所有内容从 A 复制到 B,结果是:

A/
  bar
  foo
B/
  bar
  foo
  jam
  jim

I cannot use FileUtils.cp_rbecause it copies the directory itself:

我无法使用,FileUtils.cp_r因为它复制了目录本身:

irb(main):001:0> require 'fileutils'
#=> true
irb(main):002:0> Dir['**/*']
#=> ["A", "A/bar", "A/foo", "B", "B/jam", "B/jim"]
irb(main):003:0> FileUtils.cp_r('A','B')
#=> nil
irb(main):004:0> Dir['**/*']
#=> ["A", "A/bar", "A/foo", "B", "B/A", "B/A/bar", "B/A/foo", "B/jam", "B/jim"]

Is there a better (shorter, more efficient) answer than the following?

是否有比以下更好(更短、更有效)的答案?

Dir['A/*'].each{ |f| FileUtils.cp(f,"B") }

回答by thelostspore

Using FileUtil's cp_rmethod, simply add /.at end of the source directory parameter.

使用 FileUtil 的cp_r方法,只需/.在源目录参数的末尾添加。

Example from Ruby doc below. Assumes a current working directory with src & dest directories.

下面来自 Ruby 文档的示例。假设当前工作目录包含 src 和 dest 目录。

 FileUtils.cp_r 'src/.', 'dest'

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/fileutils/rdoc/FileUtils.html#method-c-cp_r

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/fileutils/rdoc/FileUtils.html#method-c-cp_r

回答by Casual Coder

Try:

尝试:

FileUtils.cp_r(Dir['A/*'],'B')

回答by bta

When using FileUtils.cp_r, be aware that the first argument can also be a list of files. Try something like:

使用时FileUtils.cp_r,请注意第一个参数也可以是文件列表。尝试类似:

FileUtils.cp_r(Dir.glob('A/*'), 'B')