The example I gave you only copies the files, not the directories. You
may get name conflicts as a result, however.
Also the example I gave will go through every directory. If you want to
limit this you’ll need to be more specific in your code.
There are a few ways to do this, this one seems to work:
Dir.chdir ‘C:/’
files = Dir.glob(’/*.pdf’) +
Dir.glob(’/.txt’) +
Dir.glob(’**/.docx’)
files.each do |fname|
File.rename File.absolute_path(fname), ‘D:/document/’ +
File.basename(fname)
end
Nice idea! But as an example i used such .txt,.pdf extensions. But there
can be various types of files, all I have to copy. But not any folder or
directories.
The example I gave you only copies the files, not the directories. You
may get name conflicts as a result, however.
Also the example I gave will go through every directory. If you want to
limit this you’ll need to be more specific in your code.
Yes,that I understood,but What I am trying to say is in my case the file
extension can be any thing, like .vbs,.vb,rb,xlsx etc - anything. So
without hard-coding anyway to get any type of file names excluding their
directories?
The above code during renaming deleting the file also from here
“File.absolute_path(fname)”.
When you rename something, you are moving it – if you wish to retain
those files in their original place, you need to copy them to the new
destination, not rename them.
I think you may need/want to test for file-ness (and not directory- or
other-ness) of the files as well.
Personally, I’d go with the Find stdlib:
require ‘find’
def find_files(start,&blk)
Find.find(start) do |path|
if File.file?(path)
yield path
end
end
end
def gather_files(src,dst)
raise “#{src} is not a directory” unless File.directory?(src)
raise “#{dst} is not a directory” unless File.directory?(dst)
find_files(src) {|s| File.rename(s,File.join(dst,File.basename(s)))}
end
Then call gather_files with your source directory and target
directory; in your example: