2

Given:

~/Desktop/Foo.scpt contains:

(POSIX path of (path to me)) as text

Which returns:

/Users/[username]/Desktop/Foo.scpt

How do I get path /users/[username]/Desktop/ and the file name Foo.scpt as individual pieces?

6

Just ask Finder he knows how to do it :)

tell application "Finder"
     set parentpath to POSIX path of (parent of (path to me) as string)
     set filename to name of (path to me)

     display dialog parentpath
     display dialog filename
 end tell
  • 5
    How do you know that Finder is a "He" ? – Bill Nace Sep 9 '13 at 0:47
  • 2
    From his name Matthieu Riegler is French. In French, objects have gender e.g. (IIRC) tables are masculine, chairs feminine. – TechZen Aug 8 '14 at 16:33
  • "Jackie Treehorn treats objects like women, man" --The Dude – jez Oct 6 '14 at 23:02
1

This should work:

-- This script returns the full path to the directory that this script is running in

-- get the full path to be split
set pathToMe to POSIX path of (path to me as text)

-- get the path to the directory
set script1 to "dirname '" & pathToMe & "'"
set dirPath to do shell script script1

-- get the file name
set script2 to "basename '" & pathToMe & "'"
set fileName to do shell script script2

-- display the results
display dialog "Directory Path: " & dirPath & return & return & "File Name: " & fileName
1

Another option is to use text item delimiters:

set text item delimiters to "/"
POSIX path of (path to me)
text item -1 of result -- "Untitled.scpt"

If the path can end with a slash, you can use a handler like this:

on basename(x)
    if x is "/" then return "/"
    if item -1 of x is "/" then set x to text 1 thru -2 of x
    set text item delimiters to "/"
    text item -1 of x
end basename

basename("/dir1/dir2/file.txt") -- "file.txt"
basename("/dir1/") -- "dir1"
basename("/dir1/dir2/") -- "dir2"
basename("/dir1/dir2") -- "dir2"
basename("/") -- "/"

Note that text item delimiters is a property of the AppleScript object (not local to the function), but as far as I know, you don't have to restore the text item delimiters property if you don't rely on it later in the script.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .