Search code examples
macossortingapplescriptfinder

AppleScript/OSX - Sorting Issues


Okay so, I have a script to copy alpha channels from one file to another. The problem comes with the names of the one with the alpha channels having _mask in the name throwing off the sort sometimes.

Example, I have several files -

124_CHARCOAL.CR2
124_hangers.CR2
124_INDIGO.CR2
124_RED.CR2
124_TAUPE.CR2
124.CR2

124_CHARCOAL_mask.pdf
124_hangers_mask.pdf
124_INDIGO_mask.pdf
124_mask.pdf
124_RED_mask.pdf
124_TAUPE_mask.pdf

Just using tell application "Finder" to sort myList by name places things (rarely) out of order. Is there some way to fix this, or am I better off just adding some code to strip the _mask part from the file name before sorting and then re-add it back?


Solution

  • The answer to this would probably involve setting applescripts text item delimiters to ".CR2" then making a master list of text item 1 of each item in the CR2 list then manually adding "_mask.pdf" to the end of those and manually generating a new list that way.

    set myList to {"124_CHARCOAL.CR2", "124_hangers.CR2", "124_INDIGO.CR2", "124_RED.CR2", "124_TAUPE.CR2", "124.CR2"} -- this is your original sorted list of CR2 files.
    
    set maskList to {} -- prepare an empty list to receive the correctly ordered mask list.
    
    set AppleScript's text item delimiters to ".CR2"
    repeat with thisItem in myList
        set baseName to text item 1 of thisItem
        set maskName to baseName & "_mask.pdf"
        copy maskName to end of maskList
    end repeat
    set AppleScript's text item delimiters to "" -- remember to reset this to nothing
    get maskList -- this returns the properly-ordered mask list.
    

    Of course, this will only work if your naming conventions don't deviate from what you've shown us here.