Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

ruby - Copy contents of one directory to another

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

A/
  bar
  foo
B/
  jam
  jim

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

A/
  bar
  foo
B/
  bar
  foo
  jam
  jim

I cannot use FileUtils.cp_r because it copies the directory itself:

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") }
question from:https://stackoverflow.com/questions/11436680/copy-contents-of-one-directory-to-another

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...