Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby sorting a .dat file by column

Tags:

file

sorting

ruby

I am very new to ruby. I am trying to open a file .dat and sort descending by the second column. So far I was able to open the file a read it all. Please any suggestions? thanks very much.

file:


 1  88    59    74          53.8       0.00         280  9.6 270  17  1.6  93 23 1004.5
 2  79    63    71          46.5       0.00         330  8.7 340  23  3.3  70 28 1004.5
 3  77    55    66          39.6       0.00         350  5.0 350   9  2.8  59 24 1016.8
 4  77    59    68          51.1       0.00         110  9.1 130  12  8.6  62 40 1021.1
like image 892
superfloyd Avatar asked Dec 07 '25 02:12

superfloyd


1 Answers

output_lines = open("in.dat").lines.sort_by { |line| -line.split[1].to_i }
open("out.dat", "w") { |f| f.write(output_lines.join) }

This is a very basic implementation, to be used with large input data it should be tweaked a little bit (using a regexp instead of String#split, not creating a whole new string to write to the file, and so on).

like image 173
tokland Avatar answered Dec 08 '25 15:12

tokland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!