Script to add keywords to filenames / records

A variation on a theme, this script prompts the user to enter some words that will be appended to the names of the selected records.

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
-- Script that appends new keywords to filenames
-- 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"
set tDialog to display dialog "Please enter new Key Words." default answer "" with icon note buttons {"Cancel", "Continue"} default button "Continue"

--Set tNewKeyWords to display dialog "Please enter new Key Words." default answer "" with icon note  buttons {"Cancel", "Continue"} default button "Continue"
if tDialog = "" then return
set tNewKeyWords to the text returned of tDialog



tell application "EagleFiler"
	
	set _records to selected records of browser window 1
	repeat with _record in _records
		set tMyDelim to "-" -- change this value to change delimiter used
		set tOriginalName to _record's basename
		
		set tNewName to tOriginalName & tNewKeyWords & 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