Ruby on Rails: How do I move all files from one folder to another folder?
But I also need a way to rename them incase there are confli开发者_运维技巧cts.
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))
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.
精彩评论