Hello

I have some files with the date included in the filename

the format is

limited_file_11012007.dat
so this is the 11th January 2007

I have numerous files eg

limited_file_23012006.dat
limited_file_02122005.dat
limited_file_23012006.dat
limited_file_31032006.dat

I want to pick the file that is the closet day after today, ie todays date would be 11012007

How can i do this, i have tried all sorts of things, but it looks like a big bag of spanners.?

Any help appreciated

This should do the trick. Commented the last bit just in case you're not familiar with ruby.

#!/usr/bin/ruby

require 'find'

directory = "/home/peter/Ruby/test_data"
files = Array.new

#first get a list of the files

Find.find(directory) do |filename|
	filename.each do |f|
		files << f if /\.dat/ =~ f
	end
end

#to hold the difference, closest file name and its difference in time from today
diff, closest, closest_diff = nil

files.each do |f|
	#get the part of the string following the last /  
	filename = f.split("/")[-1]
	#create a time using the info in the filename
	x = Time.utc(filename.slice(17,4), filename.slice(15,2), filename.slice(13,2))
	#if the time is greater than now
	if x > Time.now
		#calculate the difference
		diff = x - Time.now
		if closest.nil?
		#if closest is empty (ie we are checking the first file)
			closest = f
			closest_diff = diff
		else
		#otherwise if the difference is smaller than the closest diff update our variables
			closest = f if diff < closest_diff
			closest_diff = diff
		end
	end

end

puts closest
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.