Sorting lines of text, not alphabetically, but buy value ($$)...

Discussion in 'Mac Programming' started by madsylar, Apr 7, 2013.

  1. madsylar
    Expand Collapse
    macrumors member

    Joined:
    May 5, 2010
    #1
    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
     
  2. ytk
    Expand Collapse
    macrumors regular

    Joined:
    Jul 8, 2010
    #2
    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.
     
  3. mfram
    Expand Collapse
    macrumors 6502a

    Joined:
    Jan 23, 2010
    Location:
    San Diego, CA USA
    #3
    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).
     
  4. 960design
    Expand Collapse
    macrumors 65816

    Joined:
    Apr 17, 2012
    Location:
    Destin, FL
    #4
    I see this and my brain says push to array and sort. The previous ideas will work as well, actually pretty dern ingenious!
     
  5. madsylar
    Expand Collapse
    thread starter macrumors member

    Joined:
    May 5, 2010
    #5
    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
     

Share This Page