Reputation: 65143
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
Upvotes: 6
Views: 5165
Reputation: 653
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
Upvotes: 6
Reputation: 47481
Another option is to run the command in the shell and deal with the response:
command = "mv *.* #{ new_directory }/"
response = system command
Dealing with existing filenames, etc. is another matter, however.
Upvotes: 0
Reputation: 31
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))
Upvotes: 3