C-Command Software Forum

AppleScript to datestamp files and strip space characters

I’m not sure if its the done thing to post scripts but here goes. I have modified one of the stock scripts so that it adds a date time stamp as a prefix to the original file name and also swaps any space characters for dashes.

I rename files because in the past I have found that meta data such as creation date can get modified and space characters cause problems when files are placed on servers or even referred to in shell scripts.

-- Script that modifies the filenames of records managed by EagleFiler
-- The files creation date is used to add a date prefix and all space characters are replaced with dashes
-- V1 dated 19th November 2020 by Skids who borrowed other peoples code and made a few small changes

-- Test before use and USE at OWN risk

-- e.g. File : "My great File Name.pdf" is renamed "2020-11-19-115723-My-great-File-Name.pdf"

tell application "EagleFiler"
	set _records to selected records of browser window 1
	repeat with _record in _records
		set _dateString to my stringFromDate(_record's creation date)
		set tOriginalName to _record's basename
		set tCleanName to my ReplaceSpaces(tOriginalName)
		set _record's basename to _dateString & tCleanName
	end repeat
end tell

on stringFromDate(_date)
	-- yyyy-mm-dd-hhmmss-
	set _string to ""
	set _string to _string & my stringFromNumber(_date's year, 4) & "-"
	set _string to _string & my stringFromNumber(_date's month as integer, 2) & "-"
	set _string to _string & my stringFromNumber(_date's day, 2) & "-"
	set _string to _string & my stringFromNumber(_date's hours, 2)
	set _string to _string & my stringFromNumber(_date's minutes, 2)
	set _string to _string & my stringFromNumber(_date's seconds, 2) & "-"
	return _string
end stringFromDate

on stringFromNumber(_number, _digitsToPad)
	return text -_digitsToPad through -1 of ("0000" & _number)
end stringFromNumber

on ReplaceSpaces(inputString)
	-- store original applescript settings just in case
	set TID to AppleScript's text item delimiters
	set AppleScript's text item delimiters to " " -- space character
	set pieces to text items of inputString -- break string apart at space characters
	set AppleScript's text item delimiters to "-" -- spaces replaced with dash character
	set inputString to pieces as text -- put string back together using dash
	--reset original as settings
	set AppleScript's text item delimiters to TID
	return inputString
end ReplaceSpaces

Yes, please post scripts here with the applescript tag.

I fixed your script. You can protect code from forum formatting and add syntax coloring by using Markdown fenced code blocks:

tell application "EagleFiler"
    -- etc.
end tell