Reputation:
I have a text file in the format of:
04-01-2010 13:25
Lorem Ipsum...
03-28-2010 15:21
Lorem Ipsum...
etc.
And I want to change the date format so that it looks like:
2010-04-01 13:25
Lorem Ipsum...
2010-03-28 15:21
Lorem Ipsum...
etc.
The problem I'm having is I can't pass a regex directly to a proc and I'm not sure how else to do it. And the code doesn't seem to be writing to the file at all. Here is my code:
def dateFix(dateLine)
dateLine = dateLine.split('-')
newDate = dateLine.slice(2), dateLine.slice(0), dateLine.slice(1)
newDate = newDate.join('-')
end
@reg = /\b\d\d-\d\d-\d\d\d\d\b/
File.open('some_file.txt', "r+") { |file|
file.each_line { |line|
date = line if line == @reg
if date
file.puts line.gsub(date, dateFix(date))
end
}
}
Upvotes: 0
Views: 1368
Reputation: 160551
Try this on:
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{2}-\d{2}-\d{4} \S+)/] )
fo.puts DateTime.strptime($1, '%m-%d-%Y %H:%M').strftime('%Y-%m-%d %H:%M')
else
fo.puts li
end
end
File.rename(INPUT_FILE, OLD_FILE)
end
File.rename(TEMP_FILE, INPUT_FILE) if (File.exist?(OLD_FILE))
This is more Ruby-like, and straightforward.
Be careful any time you attempt to read and write to the same file. Any crash will destroy the integrity of your file, so you're better to write to a temporary file, then rename the original when you've successfully finished reading/writing, then move the original to a safe backup, and move the new one in. That way, you still have your source, and your destination, allowing you to do triage if something goes wrong.
Upvotes: 2
Reputation: 87426
It is tricky to read data from a file and also write to it at the same time. I recommend reading the file a at once, closing it, then opening it for writing and writing the new contents back to it. Be sure to make a backup in case this goes wrong.
Upvotes: 2