Extract directory name, file name with root and extension in Applescript
Alec Jacobson
August 16, 2009
I posted earlier about using my last_offset function to extract the directory name and base name of a POSIX paths in applescript. This proves to be much more useful with URLs than Mac OS X file paths, especially because the default is not POSIX in applescript rather to use colons to separate files.
So I want to write a pure applescript bulletproof extractor for directory name and file name with extension.
Here's some problems right up front:
Using Finder I can't make a new folder called:
"foo:bar"
But using Finder I can make a new folder called "foo/bar"
although examining that directory in Terminal I see that the slash /
is interpreted as an escaped colon
\:
, shown here:
Now on the Terminal command line I can not make a directory called "foo/bar"
but on the Terminal command line I can make a directory called "bar:foo"
but examining that directory back in Finder I see that there the colon becomes a "/" again.
Using Script Editor and treating the alias of one of these shape-shifting directories as a string, the character renders as a slash.
These will be our extreme test cases for a bulletproof directory name and file name extractor in applescript.
Here's my attempt:
-- given a file (or folder) return a list containing
-- the path to its parent directory,
-- its name without its file extension, and
-- its file extension
on parse_file(this_file)
set default_delimiters to AppleScript's text item delimiters
-- if given file is a folder then strip terminal ":" so as to return
-- folder name as file name and true parent directory
if last item of (this_file as string) = ":" then
set AppleScript's text item delimiters to ""
set this_file to (items 1 through -2 of (this_file as string)) as string
end if
set AppleScript's text item delimiters to ":"
set this_parent_dir to (text items 1 through -2 of (this_file as string)) as string
set this_name to (text item -1 of (this_file as string)) as string
-- default or no extension is empty string
set this_extension to ""
if this_name contains "." then
set AppleScript's text item delimiters to "."
set this_extension to the last text item of this_name
set this_name to (text items 1 through -2 of this_name) as string
end if
set AppleScript's text item delimiters to default_delimiters
return {this_parent_dir, this_name, this_extension}
end parse_file