rib3ye
rib3ye

Reputation: 2923

How do I copy all files recursively to a flat directory in Ruby?

I would like to traverse several directories, recursively, and copy all the files to single directory (non-recursive).

So basically, copy:

dir1/subdir1/file1.txt
dir2/subdir1/file2.txt
dir3/subdir1/subsubdir2/file3.txt
dir4/subdir1/subsubdir2/file4.txt
dir5/subdir1/subsubdir2/subsubdir1/file5.txt


All to:

dir6/file1.txt
dir6/file2.txt
dir6/file3.txt
dir6/file4.txt
dir6/file5.txt

As far as I can tell, there isn't a way to do this, either with a method, or even building an array of the filenames with Dir.glob() and iterating through that.

If there is a way to do this in Bash, I would be happy to know it.

Upvotes: 1

Views: 292

Answers (3)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

ruby:

target = 'dir6/'
%w|dir1 dir2 dir3|.each do |dir|
  Dir["#{dir}/**/*.txt"].each do |file|
    FileUtils.cp file, target
  end
end

Upvotes: 3

korolvs
korolvs

Reputation: 118

You can try something like this:

def traverse (from, to)
  Dir.chdir(from)
  files = Dir.glob('*').select { |fn| File.file?(fn)}
  FileUtils.cp files, to
  subdirs = Dir.glob('*/')
  subdirs.each do |subdir|
    traverse subdir, to
  end
  Dir.chdir('..')
end

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

bash:

for dir in dir1 dir2 dir3
do
  for i in `find "$dir" -type f`
  do
    cp "$i" dir6
  done
done

Upvotes: 1

Related Questions