Trim the middle of a filename

Hi all,

I wonder if you could help me with a script. I want to be able to rename all the files in a folder, keeping the first 19 characters, and the last 3, and removing the rest. So from this to this…

JOBNUMB_1000000000_VERY LONG JOB DESCRIPTION v1

JOBNUMB_1000000000_v1

It would be nice if I could put it into Automator, so I can just drop a load of files on it, and it would take care of the rest. It would also mean I can share it with (even less computer savvy) colleagues.

Normally, I would look for a similar type of script and amend it, but I haven’t been able to find anything. I hope someone can help.

Thanks,

Thom

Quite simplistically, you could do this

set orgSTR to "JOBNUMB_1000000000_VERY LONG JOB DESCRIPTION v1"

set firstSTR to text 1 thru 19 of orgSTR
set lastSTR to text ((length of orgSTR) - 1) thru end of orgSTR

set allSTR to firstSTR & lastSTR

Returns

Mix the above with a droplet: http://www.macosxautomation.com/applescript/sbrt/sbrt-10.html

and you should be good.

Hi,

actually the result of your example is JOBNUMB_1000000000_ v1, the third last character is a space.

To rename a file you need to separate name and name extension, rename the name portion and append the extension again.

This code can be used as applet and droplet, save it as application

on run
	open (choose file with multiple selections allowed)
end run

on open theFiles
	repeat with aFile in theFiles
		set {fileName, fileExtension} to separateNameAndExtension(aFile)
		tell fileName to set trimmedName to text 1 thru 19 & text -3 thru -1
		if fileExtension is not "" then set trimmedName to trimmedName & "." & fileExtension
		tell application "System Events" to set name of aFile to trimmedName
	end repeat
end open

on separateNameAndExtension(f)
	tell application "System Events" to set {name:Nm, name extension:Ex} to f
	if Ex is "" or Ex is missing value then return {Nm, ""}
	return {text 1 thru ((count Nm) - (count Ex) - 1) of Nm, Ex}
end separateNameAndExtension

Perfect! This will save me so much time… thanks for your help.

Thom