I have a text file with a layout that looks like this:
2014-10-12 21:30:49
Some text here...
2013-08-30 10:40:38
Some more text here...
What the program aims to do is read through the file and change the format of the dates so that it would look like this:
10/12/2014, 21:30:49
Some text here...
08/30/2013, 10:40:38
Some more text here...
The issue is that the program only fixes the first instance of the date and quits. It doesn't seem to matter how many lines come before the first date or what comes after the first date. It just fixes the first applicable case it finds and then terminates.
Here's the code:
require 'date'
INPUT_FILE = 'some_file.txt'
OLD_FILE = 'some_file.old'
TEMP_FILE = "some_file.#{ $$ }"
File.delete(OLD_FILE) if (File.exist?(OLD_FILE))
File.open(TEMP_FILE, 'w') do |fo|
File.foreach(INPUT_FILE) do |li|
li.chomp!
if ( li[/^(\d{4}-\d{2}-\d{2} \S+)/] )
fo.puts DateTime.strptime($1, '%Y-%m-%d %H:%M:%S').strftime('%m/%d/%Y, %H:%M:%S')
else
fo.puts li
end
end
File.rename(INPUT_FILE, OLD_FILE)
end
File.rename(TEMP_FILE, INPUT_FILE) if (File.exist?(OLD_FILE))
What am I doing wrong?