Applescript to get file name without extension

10,910

This should work with filenames that contain periods and ones that don't have an extension (but not both). It returns the last extension for files that have multiple extensions.

tell application "Finder"
    set n to name of file "test.txt" of desktop
    set AppleScript's 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 more than one extension:

tell application "Finder"
    name extension of file "archive.tar.gz" of desktop -- gz
end tell
Share:
10,910
user1220109
Author by

user1220109

Updated on June 05, 2022

Comments

  • user1220109
    user1220109 almost 2 years

    I have an applescript where the user will pick one file and i need to get the name of that file minus the extension.

    I found a post on a different site that said this would work:

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

    But it returns the extensions as well. How can I get just the name of the file?

  • Lri
    Lri almost 12 years
    If the filename itself contains periods, the script currently returns the part before the first period.
  • caoimghgin
    caoimghgin almost 9 years
    Don't forget to set your text item delim to original value...set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to "." (* do your processing here *) set AppleScript's text item delimiters to oldDelims