Trim POSIX path to filename-extension, un-escape spaces etc.?

I realize this should be easy, but I’ve been banging my head on the desk trying to do it, and now it’s time to ask for help from the generous visitors to this forum.

My script will construct a POSIX path for a file that does not yet exist (because I’ll use a shell script later in the script in order to create the file). The full path might be something like this (and the filename will sometimes contain spaces):

/users/roscoe/Desktop/My\ New \File.txt

I want to put the filename and extension (not the full path) into a variable that I can display in a dialog box. In other words, I want to create a variable that looks like this:

set newname to “My New File.txt”

How can this be done?

Many thanks for any help.


I guess you’re asking for how to use “AppleScript’s text item delimiters” …

You should find a tutorial(s) on this site :slight_smile:

set theFolder to choose folder
set FileName to text returned of (display dialog "Please enter a filename" default answer "filename.txt")
set PosixPath to quoted form of POSIX path of ((theFolder as text) & FileName)

set {TID, text item delimiters} to {text item delimiters, "/"}
set displayFileName to display dialog text 1 thru -2 of (text item -1 of PosixPath)
set TID to AppleScript's text item delimiters

You really shouldn’t be escaping the spaces manually like that. Rather, when you use it in do shell script, use the form:

quoted form of thePOSIXPath

First, my apologies for inadvertently creating two threads on the same subject. This happened when I edited the subject field in my first message; I didn’t realize this would create a new thread, but it did.

Thank you for the information, which was exactly what I needed. It’s time for me to learn Apple’s text item delimiters in depth, obviously. I’m still getting used to the idea that Applescript apparently doesn’t have “trim left” or something equally straightforward…

Hallo Mr. Stanley,

thx for the advice :slight_smile:

Like stanley said it is not wise to escape characters yourself for shell scripting with applescript. Let ‘quoted form of’ do it for you and works perfectly. I have written apps that connects with a mysql client on the commandline to a database and never had problems with quoted forms.