From: Mark Woodward Date: 2007-11-25T20:10:08+09:00 Subject: Re: Moving files matching Regex Hi Stefano, On Sun, 25 Nov 2007 05:30:10 -0500 Stefano Crocco wrote: > > Not very different: > > require 'find' > require 'fileutils' > > a=[] > fglob = /(CAL|NCPH|GOH)\d{6}\.xls/ > > Find.find('.') do |f| > name = File.basename f > if name=~ fglob > a << name > FileUtils.mv f, "sent/#{name}" unless File.exist? "sent/#{name}" > end > end > > A couple of notes: > * You can create a regexp using the // syntax, instead of using > Regexp.new that's better, thanks > * when you call String#=~ you don't need to use /#{...}/, if you > already have a regexp another good thing to know. > * I think you need to pass path, and not curr_file, as the first > argument of FileUtils.mv, otherwise it won't work if the file is in a > subdirectory. There won't be any sub directories except for /sent. I've discovered from the cookbook I can use prune to ignore it. Below's where I'm up to. > > Stefano > appreciate your help, cheers, -- Mark --------------------------------------------------------------------------- require 'find' require 'fileutils' FILE_REGEX = /(CAL|NCPH|GOH)\d{6}\.xls/ SENT_DIR = "./sent/" def get_file_names fn=[] Find.find('./') do |path| Find.prune if File.basename(path) == 'sent' curr_file = File.basename(path) if curr_file =~ FILE_REGEX fn << curr_file end end fn end def move_files @a.each do |fn| new_loc = SENT_DIR + fn FileUtils.mv(fn, new_loc) if not File.exists?(new_loc) end end @a = get_file_names move_files puts @a