Search code examples
applescriptgetnameinfo

Applescript get name exception


In one of my scripts I need the file name:

set input to choose file multiple selections allowed yes
tell application "System Events"
    set {nameInfo, sourcePath} to {name of item 1 of input, POSIX path of container of item 1 of input}
end tell

But if there is a "/" in the file name e.g. "soso/lala.txt" the name comes back as "soso: lala.txt". I also tried:

do shell script "basename " & item 1 of input

but then only "lala.txt" arrives. Can I trick it somehow to get "soso/lala.txt" in return?


Solution

  • Colons and slashes in file names are error-prone in AppleScript because colons are path separators in HFS paths (the default AppleScript type) and slashes are path separators in POSIX paths

    Two suggestions:

    1. Use displayed name

      set input to choose file with multiple selections allowed
      tell application "System Events"
          set {nameInfo, sourcePath} to {displayed name of item 1 of input, POSIX path of container of item 1 of input}
      end tell
      
    2. Use the Finder

      set input to choose file with multiple selections allowed
      tell application "Finder"
          set {nameInfo, sourcePath} to {name of item 1 of input, POSIX path of (container of item 1 of input as text)}
      end tell