Reputation: 111
I have a file with rows of an SQL dump. It has dates in the format yyyy-mm-dd
(eg. 2012-08-13
)
I'd like to replace all those dates with a marker so that in the future I can populate the database with rows that are all centered around the date at the time.
For example
2012-08-13
I want to change to be stored as something like $$MAINDATE$$
2012-08-14
I want to be $$MAINDATE+1$$
This way they are all stored relative to a single date and the data will make sense backwards and forwards off the new creation date.
Then I'd like to iterate the file and replace them all with a new date based on an argument at the time. And adjusted dates based on the +1 or +100 or however many days away it will be at the end.
I think the match text is /\d{4}-\d{2}-\d{2}/
But how do I replace the text that is matched with a new term taking up and replacing the old text?
Update:
I used this to change the markers back to dates.. I doubt its pretty but its working
#iterate each line and look for the marker
while (line = infile.gets)
str = line
#replace marker with data modified by the modifier
rules = Hash[str.scan(/(\$\$MAINDATE(\+|\-)\d{1,5}\$\$)/).uniq.collect do |e|
modifyValue = e[0].split(e[1])[1].gsub("$","").to_i
if e[1] == "-" then
modifyValue = modifyValue * -1
end
[e[0], (today + modifyValue).to_s]
end ]
rules.each do |key, value|
str.gsub!(key, value)
end
#write new line to array
finishedText.push str
end
Upvotes: 1
Views: 155
Reputation: 31077
require "date"
def format_log(str, marker, refdate)
rules = Hash[str.scan(/\d{4}-\d{2}-\d{2}/m).uniq.collect{|e| [e, (Date.parse(e)-refdate).to_i]}]
rules.each do |key, value|
replacement = "%s%s" % [value >= 0 ? "+" : "", value]
str.gsub!(key, marker % replacement )
end
str
end
p format_log("2012-08-13\n2012-08-14\n2012-08-12", "$$MAINDATE%s$$", Date.today)
will output
"$$MAINDATE+0$$\n$$MAINDATE+1$$\n$$MAINDATE-1$$"
Upvotes: 1
Reputation: 1905
Something like this:
require 'date'
def munge_dates list, base_date = Date.today
date_regexp = /\d{4}-\d{2}-\d{2}/
list.map do |line|
days_difference = "%+d" % (Date.parse(line[date_regexp]) - base_date)
line.sub date_regexp,"$$MAINDATE#{days_difference}$$"
end
end
If you don't want a $$MAINDATE+0$$ in there then some conditional logic would need to be added.
Upvotes: 2