Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

Sort lists in AppleScript using the Unix sort command UNIX
To sort a list in AppleScript, try using text item delimiters and the shell command sort, like this:
set the_list to {"c", "b", "e", "a", "d"}
set old_delims to AppleScript's text item delimiters
set AppleScript's text item delimiters to {ASCII character 10} -- always a linefeed
set list_string to (the_list as string)
set new_string to do shell script "echo " & quoted form of list_string & " | sort -f"
set new_list to (paragraphs of new_string)
set AppleScript's text item delimiters to old_delims
return new_list
[robg adds:This is obviously just a sample code snippet to show what can be done by using the shell's sort command within an AppleScript, but it's a pretty good demo of the Terminal/AppleScript integration.]
    •    
  • Currently 2.50 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (6 votes cast)
 
[20,215 views]  

Sort lists in AppleScript using the Unix sort command | 9 comments | Create New Account
Click here to return to the 'Sort lists in AppleScript using the Unix sort command' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Sort lists in AppleScript using the Unix sort command
Authored by: DougAdams on May 17, '04 12:22:32PM
Somebody could earn a pretty penny from me by providing some cool shell scripts for use with text munging in AppleScript. AS is great for pushing apps around, but text and database stuff is way too for it. Here's one of my faves:
to srch_and_replace(txt, srch, repl)
	considering case
		repeat until txt does not contain srch
			set txt to (do shell script "echo " & txt & "| sed -e 's|" & srch & "|" & repl & "|' ")
		end repeat
		return txt
	end considering
end srch_and_replace

log srch_and_replace("Head Hand", "H", "l")
Friend Gnarlodious tipped me off to the sed stuff. Yeah. Mentioned here not long ago was "Wicked Cool Shell Scripts" by Dave Taylor. Good stuff there, too.

[ Reply to This | # ]
search-and-replace with sed
Authored by: hopthrisC on May 18, '04 04:18:32AM
replace

set txt to (do shell script "echo " & txt & "| sed -e 's|" & srch & "|" & repl & "|' ")

with

set txt to (do shell script "echo " & txt & "| sed -e 's|" & srch & "|" & repl & "|g' ")

(there's only one additional g near the end) and you can get rid of that repeat loop entirely. "g" stands for global and means sed should replace every occurance off the search string in the input line.

That will make the script much faster, too.

[ Reply to This | # ]

Sort lists in AppleScript using the Unix sort command
Authored by: Cezary Okupski on May 17, '09 01:20:26PM
I highly recommend Satimage.osax extension for text manipulation including text replacement according to a regular expression http://www.satimage.fr/software/en/dictionaries/dict_satimage.html

[ Reply to This | # ]
Sort lists in AppleScript using the Unix sort command
Authored by: tedw on May 17, '09 01:46:32PM

I have to agree about the Satimage osax - I use one or another of its commands in almost every applescript I write.



[ Reply to This | # ]
Sort lists in AppleScript using the Unix sort command
Authored by: Graff on May 17, '04 02:51:36PM

You are probably better off just implementing your own sort. That way you can sort any item without coercing it to text and then having to coerce it back.

Here is a simple bubblesort handler that you can call:

on BubbleSort(theList)
    if class of theList is list then
        set theSize to length of theList
        repeat with i from 1 to theSize
            repeat with j from 2 to (theSize - i + 1)
                if ((item (j - 1) of theList) > (item j of theList)) then
                    set temp to (item (j - 1) of theList)
                    set (item (j - 1) of theList) to (item j of theList)
                    set (item j of theList) to temp
                end if
            end repeat
        end repeat
        return theList
    else
        return false
    end if
end bubblesort

set the_list to {"c", "b", "e", "a", "d"}
BubbleSort(the_list)

This will sort any list that contains items which can be compared with each other using the greater than (>) operator. The list should also only contain one class of item in it, having a list that contains multiple classes of items could have odd results in the sorting. These conditions would be also be true when using the "sort" command in the shell.

I have also implemented a quicksort, a shellsort, an insertionsort, and a mergesort in AppleScript. They are not too hard to do if you know the sorting algorithm.

- Graff



[ Reply to This | # ]
Sort lists in AppleScript using the Unix sort command
Authored by: DougAdams on May 17, '04 03:16:04PM
Bubblesort is a good ol' good one, but it is intolerably slow. Compare the original post's UNIX handler and the BubbleSort handler using this as your list:
tell application "iTunes" to set the_list to (get name of every file track of library playlist 1)
It's no contest.

[ Reply to This | # ]
Sort lists in AppleScript using the Unix sort command
Authored by: jonn8n on May 17, '04 07:45:32PM
While the bubble sort routine is not the speediest, there are other vanilla AppleScript methods for sorting that are much faster and have the added benefit of keeping the data as the native data types without coercing to strings. For instance, here is a comparison using the shell sort example with the quick sort method developed by a few very accomplished AppleScripters (I'm not sure who at this point: HAS? AK? NG?)

Jon


tell application "iTunes" to set the_list to (get name of file tracks of library playlist 1)

set start_time_1 to (current date)
set sorted_list to my shell_sort(the_list)
set end_time_1 to ((current date) - start_time_1)

set start_time_2 to (current date)
my quick_sort(the_list, 1, the_list's length)
set end_time_2 to ((current date) - start_time_2)

return {end_time_1, end_time_2}

on shell_sort(the_list)
	set new_delim to {ASCII character 10}
	tell (a reference to my text item delimiters)
		set {old_delim, contents} to {contents, new_delim}
		set {the_list, contents} to {"" & the_list, old_delim}
	end tell
	return paragraphs of (do shell script "echo " & quoted form of the_list & " | sort -f")
end shell_sort

on quick_sort(a, l, r)
	--this sorts the list in place, no need to return anything
	local i, j, v
	script o
		property p : a
	end script
	set {i, j} to {l, r}
	set v to o's p's item ((l + r) div 2)
	repeat while (j > i)
		repeat while (o's p's item i < v)
			set i to i + 1
		end repeat
		repeat while (o's p's item j > v)
			set j to j - 1
		end repeat
		if (not i > j) then
			set o_s_p_s_item_i to o's p's item i
			set o's p's item i to o's p's item j
			set o's p's item j to o_s_p_s_item_i
			set {i, j} to {i + 1, j - 1}
		end if
	end repeat
	if (l < j) then quick_sort(o's p, l, j)
	if (r > i) then quick_sort(o's p, i, r)
end quick_sort


[ Reply to This | # ]
Sort lists in AppleScript using the Unix sort command
Authored by: Graff on May 17, '04 09:36:55PM

Sure, bubblesort is slow for a large number of items. That's why I said that I have a bunch of different types of sorts programmed in AppleScript. If I want to sort a large list I'd use a quicksort or a heapsort, they are O(nlogn) - much faster than bubblesort which is O(n^2). If I really needed efficient sorting I would combine a quicksort and an insertion sort (for when the quicksort partition is 10 elements or less). However, if I'm sorting a ton of elements and time is a factor then AppleScript is the wrong tool in the first place...

Bubblesort is just fine for sorting lists of a few hundred items. It is small and easily understood and doesn't clutter up a script too much. For most AppleScript tasks it is perfect.



[ Reply to This | # ]
Vanilla sorting is much better
Authored by: podd on May 18, '04 05:12:32AM

There are some very powerful, robust vanilla sorting routines in the List library at AppleMods.

Here's an example of use:

property _Loader : run application "LoaderServer"

----------------------------------------------------------------------
-- DEPENDENCIES

property _List : missing value

on __load__(loader)
    set _List to loader's loadLib("List")
end __load__

----------------------------------------------------------------------

__load__(_Loader's makeLoader())


-- DEMO
_List's sortList({"c", "b", "e", "a", "d"}) --> {"a", "b", "c", "d", "e"}

Notes: Most of this code is just auto-generated boilerplate used to load the List library. The actual sorting is done by the sortList command in the last line.

(Obligatory disclosure: I wrote the List library.)



[ Reply to This | # ]