But I also need a way to rename them incase there are conflicts.
Like if exists? then file.name = "1-"+file.name
or something like that
Maybe something like this works for you:
origin = '/test_dir'
destination = '/another_test_dir'
Dir.glob(File.join(origin, '*')).each do |file|
if File.exists? File.join(destination, File.basename(file))
FileUtils.move file, File.join(destination, "1-#{File.basename(file)}")
else
FileUtils.move file, File.join(destination, File.basename(file))
end
end
Above code works, but little mistake, You are using if File.exists?(file)
, which is checking if file exits in origin folder/or subfolder,( which is of no use, since it was read because it already exists). You need to check if file already exists in destination folder. Because of this syntax the "else" is never getting executed. And all files are getting named like "1-filename".
Correct would be to use
if File.exists? File.join(destination, File.basename(file))
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