How can I recursively copy the directory contents and exclude the source directory itself?
Asked Answered
M

2

13

Using FileUtils cp_r is usually how I copy directories, but I can't seem to exclude the base directory. This is what I wanted to work, but it doesn't:

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

source_path has sub-directories I want to copy recursively. I just don't want the actual source_path directory, just everything below it.

I tried using Dir.glob but could not get it right.

This is a Windows copy and I know I can use xcopy but want to know how to do it in Ruby.

Multifoil answered 15/10, 2013 at 21:9 Comment(0)
D
13

You want to use source_path/. instead of source_path/**, as describe in the last example of the 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

This is what cp_files.rb looks like:

require 'fileutils'
FileUtils.cp_r "source/.", 'dst', :verbose => true
Demmy answered 15/10, 2013 at 21:47 Comment(1)
If you have empty directories you wish to copy recursively, it is best practice to add a .keep file so they are not ignored from the recursive copyAllanson
D
5

Please use the FileUtils.copy_entry utility. Provide the entire path for both source & destination. It will copy recursively from source to destination excluding the source parent directory. This method preserves file types, c.f. symlink, directory… (FIFO, device files and etc. are not supported yet)

Example usage:

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)

Both of src and dest must be a path name. src must exist, dest must not exist.

If preserve is true, this method preserves owner, group, permissions and modified time. Optional use.

If dereference_root is true, this method dereference tree root. Optional use.

If remove_destination is true, this method removes each destination file before copy. Optional use.

For more information, check out the documentation.

Deprive answered 8/12, 2017 at 7:28 Comment(2)
This answer does not answer OP's questionCnut
@Cnut I believe this does answer the OP's questionAracelyaraceous

© 2022 - 2024 — McMap. All rights reserved.