943,982 Members | Top Members by Rank

Ad:
Jan 11th, 2007
0

FInding dates on files

Expand Post »
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
Similar Threads
Reputation Points: 9
Solved Threads: 0
Junior Poster in Training
sgriffiths is offline Offline
61 posts
since Jun 2006
Jan 12th, 2007
0

Re: FInding dates on files

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
pty
Reputation Points: 64
Solved Threads: 39
Posting Pro
pty is offline Offline
530 posts
since Oct 2005

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Shell Scripting Forum Timeline: two variable sin single loop
Next Thread in Shell Scripting Forum Timeline: sequential numbering





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC