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") }
To copy multiple files with the “cp” command, navigate the terminal to the directory where files are saved and then run the “cp” command with the file names you want to copy and the destination path.
In the Terminal app on your Mac, use the cp command to make a copy of a file. The -R flag causes cp to copy the folder and its contents. Note that the folder name does not end with a slash, which would change how cp copies the folder.
In order to copy a directory on Linux, you have to execute the “cp” command with the “-R” option for recursive and specify the source and destination directories to be copied.
Alternatively, right-click the folder, select Show more options and then Copy. In Windows 10 and earlier versions, right-click the folder and select Copy, or click Edit and then Copy. Navigate to the location where you want to place the folder and all its contents.
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
Try:
FileUtils.cp_r(Dir['A/*'],'B')
When using FileUtils.cp_r
, be aware that the first argument can also be a list of files. Try something like:
FileUtils.cp_r(Dir.glob('A/*'), 'B')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With