Retrieving folder information, POSIX-style

Hi All:

I'm trying to write a script that lets me compile LaTeX files I select in the Finder through the Terminal Application. Here's what I need the script to do, and I'm stumped. If it matters, I'm running AppleScript on Tiger.
  1. Select a file through the Finder. I’ve been doing that with the “choose File” scripting addition. In the standard case, that file will have a “.tex” extension. Let’s say that the file is “foo.tex”, and the alias I’m returning via choose File is “path:to the:folder:foo.tex”.

  2. I need to retrieve the folder that the file is in, and convert that folder into the POSIX format. In the example, I need to generate the string “/path/to\ the/folder/”. This is the first part where I’m stumped. I don’t know how to write this bit of code.
    As an added difficulty, I need to deal with spaces in the folder names. In the example, note that I somehow have to insert the backslash between “to” and “the”. I need this in order to get a useful string for the Terminal Application I’ll employ downstream.

  3. I need to then generate two strings based on the file name, one with the extension, one without. That is, I need to generate “foo.tex” and just plain “foo”.

Once I have these strings, I’m home free.
Any help on this would be greatly appreciated.

Cheers,
Bernhard.

Bernhard:

This script should give you everything you are looking for:

set a to (choose file)
tell application "Finder"
	set b to a's container as Unicode text --This gets the folder of the chosen file
	set c to a's name --The name of the file
	set d to a's name extension --The file extension of the file
end tell

set e to quoted form of POSIX path of b --This should deal with any spaces in the path, and give you a usable path for the terminal.
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ("." & d)
set f to c's text item 1 --This will effectively remove the dot and the file extension from the file name
set AppleScript's text item delimiters to astid
{b, c, d, e, f}
-->{"VelociDrive:Users:casdvm:Desktop:", "Dec17Chat.txt", "txt", "'/Users/casdvm/Desktop/'", "Dec17Chat"}

The Finder is only needed to get the container, file name and file extension, all other tasks can be done outside of the Finder.

The
[quoted form]
of a path will send the shell (or Terminal) the path with single quotes on either end, which should take care of any spaces in the file path.

The [text item delimiters] is a nifty way to break up a string when you are unsure what the file extension is going to be, or how long it is. If you are absolutely sure it will only be “.tex” then this also will work:

set a to (choose file)
tell application "Finder"
	set c to a's name --The name of the file
end tell
set f to (characters 1 thru -5 of c) as string

It just chops off the last 4 characters.

Hope this helps.