Search code examples
applescriptrenamefile-rename

Filename without extension in AppleScript


How to get the filename without the extension in AppleScript? For example:

Penny.Dreadful.S03E01.720p.HDTV.x264-BATV.mp4 to

Penny.Dreadful.S03E01.720p.HDTV.x264-BATV

One file to work enough for me but could be in for more file. The following code takes the file name but with the extension. I don't want the extension. Thanks for your help.

try
set theNames to {}
tell application "Finder"
   repeat with i in (get selection)
       set end of theNames to name of i
   end repeat
end tell
set {TID, text item delimiters} to {text item delimiters, return}
set the clipboard to theNames as text
set text item delimiters to TID
end try

Solution

  • Try this, instead of the try block the script checks for empty selection and the fileName is extracted by subtracting the extension if there is one.

    set theNames to {}
    tell application "Finder"
        set theSelection to selection
        if theSelection is {} then return
        repeat with anItem in theSelection
            set {name:fileName, name extension:fileExtension} to anItem
            set end of theNames to my removeExtension(fileName, fileExtension)
        end repeat
    end tell
    set {TID, text item delimiters} to {text item delimiters, return}
    set the clipboard to theNames as text
    set text item delimiters to TID
    
    on removeExtension(Nm, Ex)
        if Ex is missing value or Ex is "" then return Nm
        return text 1 thru ((count Nm) - (count Ex) - 1) of Nm
    end removeExtension