Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

madsylar

macrumors member
Original poster
May 5, 2010
58
13
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
 
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:

Code:
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):

Code:
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.
 
The 'sort' command line utility will do this operation. This is available in the shell (Terminal.app).

Code:
$ 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).
 
I see this and my brain says push to array and sort. The previous ideas will work as well, actually pretty dern ingenious!
 
Thank you

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
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.