Skip to content

Instantly share code, notes, and snippets.

@caius
Last active December 25, 2015 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caius/7023161 to your computer and use it in GitHub Desktop.
Save caius/7023161 to your computer and use it in GitHub Desktop.
Written to solve the problem of sorting a text file posed at http://devblog.avdi.org/2013/10/16/sorting-lines-in-5-languages/ in Applescript
--
-- avdi-sort.applescript
-- Written to solve the problem of sorting a text file posed
-- at http://devblog.avdi.org/2013/10/16/sorting-lines-in-5-languages/
--
-- Created by Caius Durling on 2013-10-17.
-- Probably not the best applescript ever, but it works.
--
-- USAGE:
-- $ osascript avdi-sort.scpt to_sort.txt sorted.txt
-- Grabbed from http://www.macosxautomation.com/applescript/sbrt/sbrt-05.html
-- to save writing my own implementation. Ungolfed.
on sort_file(my_list)
local index_list, sorted_list, low_item, this_item, low_item_index
set the index_list to {}
set the sorted_list to {}
repeat (the number of items in my_list) times
set the low_item to ""
repeat with i from 1 to (number of items in my_list)
if i is not in the index_list then
set this_item to item i of my_list as text
if this_item is not "" then -- Filter out blank newlines
if the low_item is "" then
set the low_item to this_item
set the low_item_index to i
else if this_item comes before the low_item then
set the low_item to this_item
set the low_item_index to i
end if
end if
end if
end repeat
set the end of sorted_list to the low_item
set the end of the index_list to the low_item_index
end repeat
return the sorted_list
end simple_sort
on basename(fileName)
-- Get path to file so we can read it
tell application "Finder" to set baseDir to POSIX path of ((container of (path to me)) as alias)
return (baseDir & fileName)
end
on run argv
-- Split/join by newlines in this script
set text item delimiters to "\n"
-- Find the proper paths of the passed files
set inputFile to basename(item 1 of argv)
set outputFile to basename(item 2 of argv)
-- Read & sort the files
set fileLines to text items of (read inputFile as «class utf8»)
set sortedOutput to sort_file(fileLines) as string
-- Write the output! Creates file if required
open for access outputFile with write permission
write sortedOutput to outputFile as «class utf8»
end run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment