From: Daniel Finnie Date: 2008-04-23T13:38:31+09:00 Subject: Re: Extract date from filenames using regex Hi, You can use File.mtime(file_name) which will return a Time object. You can also match with /\d+/ (one or more digits): >> ("sdf555sadfsdfg")[/\d+/] => "555" But watch out!: >> ("sdf555sadfs5867dfg")[/\d+/] => "555" For a nice, object-oriented approach to file manipulation in Ruby, you might want to check out Pathname in the standard library: http://www.ruby-doc.org/stdlib/libdoc/pathname/rdoc/index.html Dan On Tue, Apr 22, 2008 at 11:48 PM, Clement Ow wrote: > I have my code which looks like this: > >> delete= 5 + 2 #escape counting in weekends i.e Sat,Sun > >> folders = $del_path > >> puts delete_date = DateTime.now - delete > > >> regexp = Regexp.compile(/(\d{4}\d{2}\d{2})/) > > >> fileData = Struct.new(:name, :size) > >> deleted_files = [] > > >> folders.each do |folder| > >> Dir.glob(folder+"/*") do |file| > >> match = regexp.match(File.basename(file)); > >> if match > >> file_date = DateTime.parse(match[1]) > When my file name is in the format, 20080331 for example, the script > will run successfully. However, if the filename has additional > characters added to it, say, risk20080331, it'll run an error. And i > reckon it's the cause of the above line. > > >> size = (File.size(file))/1024 > >> if delete_date > file_date > >> deleted_files << fileData.new(file,size) > >> FileUtils.rm_r file > > >> if File.exist?(file)==false > >> puts "Files/Folders deleted: #{file} size: #{size} KB" > >> end #if > >> end #if > >> end #if > >> end #do > >> end #each > >> end #if > > So is there any way I can extract the date using regex or whichever way > simpler so I can compare the deletion date and execute the rm_r command? > Thanks! > -- > Posted via http://www.ruby-forum.com/. > >