Reputation: 59
I have a tab delimited file, for which I need to concatenate selective columns into a key-value pair. Let's say my first three columns stay the same, but after that, I can expect any number of columns. All the columns after the third should concatenate into a key-value pair.
Here is my data set:
col1 col2 col3 col4 col5
1 2 3 4 5
Result
col1 col2 col3 col4|col5
1 2 3 col4 => 4 | col5 => 5
Upvotes: 0
Views: 229
Reputation: 27528
If you have the following input file:
col1,col2,col3,col4,col5
1,2,3,this,that
2,3,4,some,more
3,4,5,a,b
Then pulling off the header, splitting and destructuring each line can be done with something like:
header, *lines = File.readlines('var.txt')
header = header.split(',')
header[-1].chomp!
rest_fields = header.slice(3..-1)
recs = lines.map do |line|
line.chomp!
f1, f2, f3, *rest = line.split(',')
pairs = {}
rest_fields.each do |f|
pairs[f] = rest.shift
end
[f1, f2, f3, pairs]
end
recs.each do |rec|
puts rec.inspect
end
Running that gives:
["1", "2", "3", {"col4"=>"this", "col5"=>"that"}]
["2", "3", "4", {"col4"=>"some", "col5"=>"more"}]
["3", "4", "5", {"col4"=>"a", "col5"=>"b"}]
Is this what you're after?
Upvotes: 1