From: Sam Fent Date: 2007-03-15T02:27:00+09:00 Subject: Re: Copying files and changing their names Sam Fent wrote: > If I wanted to change example2.txt to example-final.txt, and test3.txt > to test-final.txt, how could I iterate throught the files to find the > file with the highest number? Ok, so I worked it out myself, as I probably should have from the beginning. This is almost certainly not the most efficient code, in that it iterates over the same directories several times, but here it is, in case any future person wants to do the same thing (or any present person wants to make it more efficient). require 'find' require 'fileutils' usedNames = [] Find.find('.') do |f| if (File.file?(f) and f.match(/txt$/)) name = f[/.*V/][0..-2] if (!usedNames.include?(name)) usedNames += [name] versions = [] # find the latest version number Find.find('.') do |f| if (File.file?(f) and f.match(/#{name}.*txt$/)) versionNumber = f[name.length+1..-5] versions += [versionNumber] end end versions = versions.sort lastVersionNumber = versions[versions.length-1] # copy file and re-name it FINAL if (!lastVersionNumber.match(/.*FINAL.*/)) Find.find(name+"V"+lastVersionNumber+".txt") do |g| puts "Changing file " + g + " to: " + g.sub(/#{lastVersionNumber}/,"_FINAL") FileUtils.cp(g,g.sub(/#{lastVersionNumber}/,"FINAL")) end end end end end -- Posted via http://www.ruby-forum.com/.