Skip to main content
4 of 5
Rollback to Revision 2
200_success
  • 145.6k
  • 22
  • 191
  • 481

Applescript to change file extensions

I'm new at scripting, but I thought it would be handy to have a script that would change the extensions of selected files in Finder. I run this script from an automator service so that batch changing extensions in Finder is always just a right click away.

So far, it has worked as I expect, but since this is one of my first scripts, my question is: is there a cleaner way to obtain this functionality? Can anyone point out a case I haven't thought of in which this would fail?

What this script does:

  • Asks the user for a new extension.
  • Adds the new extension to any files that don't already have one.
  • Changes the extension in other files even if it's a hidden file or has multiple points.

A test case that does not function correctly:

  • The selected file's name has multiple points, but no extension. Here, my script replaces the text after the last point with the new extension.

Here's the code:

# Ask user for new extension to be used
set newExt to the text returned of (display dialog "Enter extension:" default answer "Do not include first point")


tell application "Finder"

    # Make a list of the selected files in Finder
    set selFiles to selection as list

    set TID to AppleScript's text item delimiters

    repeat with eachFile in selFiles
    
        # Make a text item list of the file name delimited by points
        set filePath to eachFile as text
        set AppleScript's text item delimiters to {":"}
        set fileName to last text item of filePath
        set AppleScript's text item delimiters to {"."}
        set textItems to text items of fileName
    
        # Handle case where there is currently no extension, but one should be added.
        if number of textItems is 1 then
            set name of eachFile to fileName & "." & newExt
        
        # If an extension does already exist...
        else
        
            set newName to ""
            set numItems to number of items in textItems
            set n to 1
        
            repeat numItems times
            
                # If the current text item is not the extension, add it & "." to the new file name.  No need here to consider the last text item since it's the old extension and we want to get rid of it.
                if n is not numItems then
                    set newName to newName & item n in textItems & "."
                    set n to n + 1
                end if
            
            end repeat
        
            set name of eachFile to newName & newExt
        
        end if
    
    end repeat

    # Is this line necessary?  I just saw it at the end of someone else's script that had earlier set TID to AppleScript's text item delimiters.
    set AppleScript's text item delimiters to TID

end tell

Thanks for the feedback and feel free to use this if it would be useful for you.