Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy contents of one directory to another

Tags:

ruby

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") }
like image 1000
Phrogz Avatar asked Jul 11 '12 15:07

Phrogz


People also ask

How do I copy all contents from one directory to another?

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.

How can I copy the contents of a folder to another folder in a different directory using terminal?

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.

How do I copy an entire folder to another 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.

How do I copy the contents of a folder?

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.


3 Answers

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

like image 169
myconode Avatar answered Nov 04 '22 23:11

myconode


Try:

FileUtils.cp_r(Dir['A/*'],'B')
like image 33
Casual Coder Avatar answered Nov 04 '22 22:11

Casual Coder


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')
like image 27
bta Avatar answered Nov 04 '22 23:11

bta