From: Paul Archer Date: 2009-07-23T05:12:07+09:00 Subject: Re: safe move/copy with incrementing filenames? --792783111-1811361967-1248293424=:11583 Content-Type: MULTIPART/MIXED; BOUNDARY="792783111-1811361967-1248293424=:11583" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --792783111-1811361967-1248293424=:11583 Content-Type: TEXT/PLAIN; CHARSET=ISO-8859-15; format=flowed Content-Transfer-Encoding: 8BIT Content-ID: Here's what I came up with (incorporating your code, pharrington): def safe_move(source, dest, digits=2 ) source.to_a.each do |src| if File.directory?(dest) d = File.join(dest, File.basename(src) ) else d = dest end count = 0 unique_name = d while File.exists?(unique_name) count += 1 ext = File.extname(d) unique_name = File.join( File.dirname(d), File.basename(d, ext) + sprintf("_%0#{digits}d", count) + ext ) end d = unique_name return FileUtils.mv(src, d) end end Paul 2:30am, pharrington wrote: >> On Jul 20, 10:50�pm, Paul Archer wrote: >> So, I'm working on some DAM (digital asset management) scripts, and I want >> to make sure that I don't overwrite any files when I move or copy them. >> I was about to start working on a move method that would add a number to >> the destination filename if the name already exists. (IE >> mv('pma_20090720_1234.jpg', 'archive/2009/07') might create an >> 'archive/2009/07/pma_20090720_1234-1.jpg if pma_20090720_1234.jpg exists.) >> >> Question: is there already a module that can do that? >> >> Paul > > I've just been doing this: > > def unique(filename) > count = 0 > unique_name = filename > while File.exists?(unique_name) > count += 1 > unique_name = "#{File.join( > File.dirname(filename), > File.basename(filename, ".*"))}_#{count}#{File.extname > (filename)}" > end > unique_name > end > > there's probably a better way though > --792783111-1811361967-1248293424=:11583-- --792783111-1811361967-1248293424=:11583--