Applescript to get file name without extension

I have applescript where the user will select a single file, and I need to get the name of this file minus the extension.

I found a post on another site that says this will work:

tell application "Finder" set short_name to name of selected_file end tell 

But it also returns extensions. How can I get only the file name?

+4
source share
4 answers

You can specify the Finder or System Events to expand the name and remove this part from the full name. This will also avoid problems with names with periods in them or extensions that may not be what you think.

 set someItem to (choose file) tell application "System Events" to tell disk item (someItem as text) to set {theName, theExtension} to {name, name extension} if theExtension is not "" then set theName to text 1 thru -((count theExtension) + 2) of theName -- the name part log theName & tab & theExtension 
+4
source

This should work with file names that contain periods and those that do not have an extension (but not both). It returns the latest extension for files with multiple extensions.

 tell application "Finder" set n to name of file "test.txt" of desktop set AppleScript text item delimiters to "." if number of text items of n > 1 then set n to text items 1 thru -2 of n as text end if n end tell 

name extension also returns the last extension for files with several extensions:

 tell application "Finder" name extension of file "archive.tar.gz" of desktop -- gz end tell 
+2
source

Here's a script to get only file names.

 set filesFound to {} set filesFound2 to {} set nextItem to 1 tell application "Finder" set myFiles to name of every file of (path to desktop) --change path to whatever path you want end tell --loop used for populating list filesFound with all filenames found (name + extension) repeat with i in myFiles set end of filesFound to (item nextItem of myFiles) set nextItem to (nextItem + 1) end repeat set nextItem to 1 --reset counter to 1 --loop used for pulling each filename from list filesFound and then strip the extension --from filename and populate a new list called filesFound2 repeat with i in filesFound set myFile2 to item nextItem of filesFound set myFile3 to text 1 thru ((offset of "." in myFile2) - 1) of myFile2 set end of filesFound2 to myFile3 set nextItem to (nextItem + 1) end repeat return filesFound2 
0
source

This script uses ASObjC Runner to parse file paths. Download ASObjC Runner here.

 set aFile to choose file tell application "ASObjC Runner" to set nameS to name stub of (parsed path of (aFile as text)) 
0
source

All Articles