C-Command Software Forum

AppleScript - to clean record / file names

Hi,
Here is a script that modifies the file names of records in EagleFiler. While MAcOS allows tags I prefer what I call keywords as part of the filename. Using Keywords this way means that they are available across all operating systems that allow long names. The script replaces characters with a delimiter, I use the dash character. Multiple delimiters will be removed by my crude loop; I’m sure there is a better way of doing this but have not found it yet. To change the delimiter just edit the one line indicated.

Second attempt at posting the script, I’m not allowed to save my edit of the first

-- Script that modifies the filenames of records managed by EagleFiler
-- removes spaces, underscores and points replacing them with a dash
-- adds a trailing dash before the dot extension
-- Quite slow but faster than doing it manually
-- 0.45 seconds per record on 2013 i7

-- V1 dated 25th November 2020 by Skids

-- Test before use and USE at OWN risk

-- e.g. File : "My great File Name.pdf" is renamed "My-great-File-Name-.pdf"

tell application "EagleFiler"
	set _records to selected records of browser window 1
	repeat with _record in _records
		set tOriginalName to _record's basename
		set tMyDelim to "-" -- change this value to change delimiter used
		set tNewName to tOriginalName & tMyDelim
		set tNewName to my ReplaceText(" ", tMyDelim, tNewName) -- replace spaces
		set tNewName to my ReplaceText("_", tMyDelim, tNewName) -- replace underscore
		set tNewName to my ReplaceText(".", tMyDelim, tNewName) -- replace points
		
		-- now remove multiple repeats of the delimiter
		set tCounter to 0
		repeat until tCounter > 9
			set tCounter to tCounter + 1
			set tCleanName to my ReplaceText(tMyDelim & tMyDelim, tMyDelim, tNewName)
			if tNewName = tCleanName then
				exit repeat
			else
				set tNewName to tCleanName
			end if
		end repeat
		set _record's basename to tNewName
	end repeat
end tell


on ReplaceText(find, replace, subject)
	set prevTIDs to text item delimiters of AppleScript
	set text item delimiters of AppleScript to find
	set subject to text items of subject
	
	set text item delimiters of AppleScript to replace
	set subject to "" & subject
	set text item delimiters of AppleScript to prevTIDs
	
	return subject
end ReplaceText