How to truncate filenames after X number of characters using Automator or AppleScript

applescriptautomationautomatorfinder

I have IFTTT sending several new desktop wallpapers per day from Reddit to Dropbox. These wallpapers arrive often with very long filenames. I need a way to automatically shorten their names (without renaming to date and time) when they're downloaded to my Mac by Dropbox.

  • I want the action to run automatically, so it can't require me to select Finder items or supply the number of characters to keep
  • It needs to run by itself as a folder action or AS via Hazel.

Could someone please give me an Automator folder action or AppleScript I can put in Hazel to truncate the filenames after X number of characters?

Best Answer

Do we have to be concerned about the names being the same? If not, this should work for you as an embedded AppleScript in Hazel:

tell application "Finder"
    set original_name to name of theFile
    set short_name to characters 1 thru 10 of original_name as string
    set name of theFile to (short_name & ".png" as string)
end tell

You'd set Hazel to run this rule on "any file" then "Run AppleScript" (embedded).

You can change the number of characters easily. I picked ten. Do what works for you. Also, I guessed that your images are ".png" files-- you would change that to ".jpg" or whatever.

I hope this helps you!