3/30/2018 - 11:40 PM

Trim Filenames by Character Count

# Trim Filenames by Character Count

set userFolder to choose folder
set dialogResult to display dialog "Numbers of characters to remove:" buttons {"Cancel", "At beginning", "At end"} default answer 0 cancel button "Cancel"
set buttonResult to button returned of dialogResult
set numberOfChars to text returned of dialogResult as integer
if buttonResult = "At end" then set numberOfChars to -numberOfChars

tell application "Finder"
	repeat with eachFile in (get document files in userFolder)
		set fullName to name of eachFile
		set {textDelimiters, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "."}
		if (count of text items of fullName) is greater than 1 then
			set properName to my Trim((text items 1 thru -2 of fullName) as text, numberOfChars)
			set newName to ({properName, (get last text item of fullName)}) as text
			set newName to my Trim(fullName, numberOfChars)
		end if
		set AppleScript's text item delimiters to textDelimiters
		set name of eachFile to newName
	end repeat
end tell

on Trim(t, n)
	if n > 0 then
		return text (n + 1) thru -1 of t
		return text 1 thru (n - 1) of t
	end if
end Trim