Script to sanitise file names

If you put this handler inside a Script Library …

-- Replace non-alphanumeric characters with delimiter

use AppleScript version "2.4"
use framework "Foundation"
use scripting additions

set theFilename to "_Bla - Blubb? 0123 a"
set theDelimiter to " "
set theFilename_sanitized to my sanitizeText(theFilename, theDelimiter)

on sanitizeText(theText, theDelimiter)
	try
		set theString to current application's NSString's stringWithString:theText
		set theCharacterSet to current application's NSCharacterSet's alphanumericCharacterSet()
		set theComponents to theString's componentsSeparatedByCharactersInSet:(theCharacterSet's invertedSet())
		
		set newText_list to {}
		repeat with thisComponent in theComponents
			set thisComponent to thisComponent as string
			if thisComponent ≠ "" then
				set end of newText_list to thisComponent
			end if
		end repeat
		
		set d to AppleScript's text item delimiters
		set AppleScript's text item delimiters to theDelimiter
		set theText_sanitized to newText_list as text
		set AppleScript's text item delimiters to d
		return theText_sanitized
		
	on error error_message number error_number
		activate
		if the error_number is not -128 then display alert "Error: Handler \"sanitizeText\"" message error_message as warning
		error number -128
	end try
end sanitizeText

… and call it in your Smart Rule like

set theFilename_sanitized to script "Your Script Library Name"'s sanitizeText(theFilename, theDelimiter)

it should do what you want.

To create a Script Library:

4 Likes