FInding dates on files

Reply

Join Date: Jun 2006
Posts: 61
Reputation: sgriffiths is an unknown quantity at this point 
Solved Threads: 0
sgriffiths sgriffiths is offline Offline
Junior Poster in Training

FInding dates on files

 
0
  #1
Jan 11th, 2007
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
Reply With Quote Quick reply to this message  
Join Date: Oct 2005
Posts: 521
Reputation: pty is on a distinguished road 
Solved Threads: 37
pty's Avatar
pty pty is offline Offline
Posting Pro

Re: FInding dates on files

 
0
  #2
Jan 12th, 2007
This should do the trick. Commented the last bit just in case you're not familiar with ruby.


Shell Scripting Syntax (Toggle Plain Text)
  1. #!/usr/bin/ruby
  2.  
  3. require 'find'
  4.  
  5. directory = "/home/peter/Ruby/test_data"
  6. files = Array.new
  7.  
  8. #first get a list of the files
  9.  
  10. Find.find(directory) do |filename|
  11. filename.each do |f|
  12. files << f if /\.dat/ =~ f
  13. end
  14. end
  15.  
  16. #to hold the difference, closest file name and its difference in time from today
  17. diff, closest, closest_diff = nil
  18.  
  19. files.each do |f|
  20. #get the part of the string following the last /
  21. filename = f.split("/")[-1]
  22. #create a time using the info in the filename
  23. x = Time.utc(filename.slice(17,4), filename.slice(15,2), filename.slice(13,2))
  24. #if the time is greater than now
  25. if x > Time.now
  26. #calculate the difference
  27. diff = x - Time.now
  28. if closest.nil?
  29. #if closest is empty (ie we are checking the first file)
  30. closest = f
  31. closest_diff = diff
  32. else
  33. #otherwise if the difference is smaller than the closest diff update our variables
  34. closest = f if diff < closest_diff
  35. closest_diff = diff
  36. end
  37. end
  38.  
  39. end
  40.  
  41. puts closest
Note to self... pocket cup
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Shell Scripting Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC