From: Stefano Crocco Date: 2007-11-25T19:30:10+09:00 Subject: Re: Moving files matching Regex Alle domenica 25 novembre 2007, Mark Woodward ha scritto: > Hi all, > > A question relating to the code below. > > What I'm trying to do is: > Files named CAL221107.xls, NCPH141202.xls or GOH333333.xls for example > in the current directory should be appended to an array (just the file > name, not the full path) and moved to ./sent/ > > It seems to be working, but is there a more Rubyish way of doing it? > > ------------------------------------------------------------------------- > require 'find' > require 'fileutils' > > a=[] > fglob = Regexp.new('(CAL|NCPH|GOH)\d{6}\.xls') > > Find.find('./') do |path| > curr_file = File.basename(path) > if curr_file =~ /#{fglob}/ > a << curr_file > new_file = "./sent/#{curr_file}" > FileUtils.mv(curr_file, new_file) if not File.exists?(new_file) > end > end > > puts a > > ------------------------------------------------------------------------- > > thanks, 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 * when you call String#=~ you don't need to use /#{...}/, if you already have a regexp * 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. Stefano