Reputation: 31
Forgive me, I am very new to Ruby and relatively new to programming in general. My problem is probably not hard, but I have googled until my fingers bled looking for a solution and I just cant get it.
I have a line of text that looks like this:
6 19 11 28 22 localhost G6UI ip0 cameraLink cameraLinkMissingScans 15116
After all is said and done, I want it to look like this:
6.19.2014,11.28.22,localhost,G6UI,ip0,cameraLink cameraLinkMissingScans 15116
I have accomplished this in Bash (I am essentially just making a CSV file, with the time and date formatted the way I want it) but, for reasons to lengthy to explain, Id like to do it with Ruby.
I have a start, although its probably a bit sad:
myLineOfText.sub!(/[^-a-zA-Z0-9]/,'\1.\2.')
Which gives me this:
6..19 11 28 22 localhost G6UI ip0 cameraLink cameraLinkMissingScans 15116
Any help would be greatly appreciated, I just need something to get me started.
Thanks in advance.
Upvotes: 0
Views: 65
Reputation: 110675
With questions such as this one, the answer depends on what is fixed and what is variable in the data's format. I have assumed:
dd.mm.2014
I don't think a regex is the right tool for the formating; rather just split the string on spaces and form the new string by using a series of String#join
's, combining the resulting substrings in the obvious way:
s = "6 19 11 28 22 localhost G6UI ip0 cameraLink cameraLinkMissingScans 15116"
a = s.split(' ')
#=> ["6", "19", "11", "28", "22", "localhost", "G6UI", "ip0", "cameraLink",
# "cameraLinkMissingScans", "15116"]
a[0]+'.'+a[1]+'.2014,'+a[2..4].join('.')+','+a[5..7].join(',')+','+
a[8..-1].join(' ')
#=> "6.19.2014,11.28.22,localhost,G6UI,ip0,cameraLink cameraLinkMissingScans 15116"
Upvotes: 0
Reputation: 22821
If you can be sure the format always remains the same, you can do:
str.sub!(/(\d+) (\d+) (\d+)/,'\1.\2.\3').gsub!(/ /,',')
Example:
str='6 19 11 28 22 localhost G6UI ip0 cameraLink cameraLinkMissingScans 15116'
str.sub!(/(\d+) (\d+) (\d+)/,'\1.\2.\3').gsub!(/ /,',')
puts str
=> "6.19.11,28,22,localhost,G6UI,ip0,cameraLink,cameraLinkMissingScans,15116"
Upvotes: 1