[NTLUG:Discuss] Sort question
Preston Hagar
prestonh at gmail.com
Thu Apr 5 10:10:16 CDT 2012
On Thu, Apr 5, 2012 at 8:40 AM, Fred <fredstevens at yahoo.com> wrote:
> I have a long table with 6 columns of numbers. I want each row of 6 numbers to
>
> be arranged in ascending order and separated by some delimiter such as
> comma or space, like this:
>
> 53 17 3 24 9 33
>
> 16 8 42 29 1 20
> <etc>
>
> would become
>
> 3 9 17 24 33 53
> 1 8 16 20 29 42
> <etc>
>
> My code was getting really stupid but that was maybe because it was
> really late. Actually, I don't know how to do this. I tried openoffice calc
> at first but it scrambled the table. I put the data into a text file but none
> of the single digit numbers have a leading zero so none of my feeble
>
> attempts at scripting worked very well.
>
> I might mention that I also have the table in csv format instead of space
> separated, if that might help.
>
>
> Any suggestions?
>
> Thanks,
> Fred
>
Below is a little ruby script that should do it, I did it for a CSV
file, but you could modify it to use the space file by replacing the ,
in the split function with a space.
Save the code into a plain text file and name it something (I
suggested numSort.rb). Then be sure to chmod +x it to make it
executable:
chmod +x numSort.rb
See the comments (lines starting with #) for other instructions.
#################### Code starts below this line #########################
#!/usr/bin/env ruby
# edit the line below and replace numberfile.csv with the name of your
file
# run the program like this:
# ./numSort.rb > sorted_file.csv
# read in file, replace numberfile.csv with the name of your csv file
numLines = IO.readlines("numberfile.csv")
# go through each line of the file
numLines.each do |currLine|
# make a temporary array
tmpArray = []
# for each line, devide on the commas
currLine.split(',').each do |currVal|
# if you have a value, add it to the array
if currVal != nil
tmpArray.push(currVal.strip.to_i)
end
end
# now sort them and print them back out
tmpStr = ''
tmpArray.sort.each do |currVal|
tmpStr += "#{currVal},"
end
tmpStr = tmpStr.chop
if tmpStr.length > 2
puts tmpStr
end
end
############# End Code ############################
Hope this helps.
Preston
More information about the Discuss
mailing list