Sorting with AppleScript (AppleScrunix Style)
Friday 29 April 2011 - Filed under automation + gaps + Technology
As there is no built-in sort function in AppleScript you have to create your own. A common way of sorting lists is to use the repeat function… cycling through the list comparing items as you progress. One of the more efficient approaches is a bubble sort. You can find an excellent example in Lesson 18, “Working with Lists and Records” in Sal Saghoian’s book, AppleScript 1-2-3.
This AppleScript bubble sort was taken in part from Sal’s book:
set fruit to {"pears", "bananas", "apples", "grapes", "watermelon", "pineapple"}
set last_swap_position to length of fruit
repeat while last_swap_position > 0
set comparisons_needed to last_swap_position - 1
set last_swap_position to 0
repeat with i from 1 to comparisons_needed
if item i of fruit > item (i + 1) of fruit then
set swap_item to item i of fruit
set item i of fruit to item (i + 1) of fruit
set item (i + 1) of fruit to swap_item
set last_swap_position to i
end if
end repeat
end repeat
return fruit
= {"apples", "bananas", "grapes", "pears", "pineapple", "watermelon"}
Using AppleScrunix you can sort the same list using a shell script sort command:
set fruit to {"pears", "bananas", "apples", "grapes", "watermelon", "pineapple"}
set text item delimiters to {ASCII character 10}
set fruit to fruit as string
set fruit to paragraphs of (do shell script "echo " & quoted form of (fruit) & " | sort -f")
set text item delimiters to ""
return fruit
= {"apples", "bananas", "grapes", "pears", "pineapple", "watermelon"}
Though it doesn’t save much coding, it executes faster, especially as the lists get longer. Using sort, via shell, also allows for files/lists to be sorted without having to open them. I will cover that in a future post.
We will continue to delve deeper into AppleScript & AppleScrunix in future posts.
2011-04-29 » Russ Leseberg
13 August 2011 @ 3:01 am
Looks very handy, I’m set to try this & wondering if there’s a way to do this with 2-dimensional lists.
13 August 2011 @ 12:55 pm
Absolutely. Can you provide me a sample list to sort?
1 June 2012 @ 3:38 am
Is there an easy way or built in switch that will allow me to sort a list with varying cases?
Original = grapes, Apples, Cucumbers, bananas.
end result = Apples, bananas, Cucumbers, grapes
1 June 2012 @ 7:27 am
If I understand your question correctly, that is how the two samples are currently written to react. Have you tried running the scripts as shown the post against your sample data?