PDA

View Full Version : Sorting lines of text, not alphabetically, but buy value ($$)...




madsylar
Apr 7, 2013, 10:21 PM
Hi all,

I'm having a lot of difficulty researching this, I don't even know if it's possible anymore. We have a text file like:

Apples ($100)
Bananas ($400)
Desktop Computers ($30)
Dogs and Cats ($250)

We need to sort it by the value.

Bananas ($400)
Dogs and Cats ($250)
Apples ($100)
Desktop Computers ($30)

I don't have much experience with applescript but in other programming languages i'd just split this in a 2d array and sort it. Is there such thing in applescript?

Could anyone just point me out in a direction? There isn't such thing as an 2d array in applescript and I don't know if this is possible.

Thank you.

Leo



ytk
Apr 7, 2013, 11:05 PM
So why do it in AppleScript? Even if you have to do it in AppleScript for some reason, just farm it out to another language to do the heavy lifting.

Here's a Ruby one liner to do what you want:

puts STDIN.read.split("\n").sort{ |x,y| y.match(/\$[0-9]+/).to_s[1..-1].to_i <=> x.match(/\$[0-9]+/).to_s[1..-1].to_i }

And here's the whole thing in an AppleScript statement (with appropriate mangling):

do shell script "ruby -e 'puts STDIN.read.split(%Q(\\n)).sort{ |x,y| y.match(/\\$[0-9]+/).to_s[1..-1].to_i <=> x.match(/\\$[0-9]+/).to_s[1..-1].to_i }' < ~/data.txt"

Just modify the ~/data.txt statement to point to your file. Also, don't do this in AppleScript, because AppleScript sucks :p.

mfram
Apr 7, 2013, 11:30 PM
The 'sort' command line utility will do this operation. This is available in the shell (Terminal.app).

$ cat data.txt
Apples ($100)
Bananas ($400)
Desktop Computers ($30)
Dogs and Cats ($250)

$ sort -r -n -t $ -k 2 < data.txt
Bananas ($400)
Dogs and Cats ($250)
Apples ($100)
Desktop Computers ($30)


That means sort reverse (-r), numerical (-n), using "$" as field delimiter (-t $), using the second field (-k 2).

960design
Apr 8, 2013, 06:30 AM
I see this and my brain says push to array and sort. The previous ideas will work as well, actually pretty dern ingenious!

madsylar
Apr 8, 2013, 07:05 AM
Thank you ytk and mfram for the quick answers and practical solutions. Agreed 960design!

Thanks again for the help, I wish I had asked before instead of spending so much time trying to do this in applescript.

Leo