Format text string to MAC address

I’m a network engineer, and deal with MAC addresses all the time. Often, they come without the colons in between each pair (octet). Sometimes I have an entire list or table of them!

I’m need to create an AppleScript to format a selected string (or strings) of 12 characters and insert a colon between each two characters.

Example:
64167F59F879

becomes
64:16:7F:59:F8:79

Thank you!

The following is the basic code that will do what you want. Additional code is required to work through a list or table of addresses, but more information is required to include that in the script.

set macAddress to "64167F59F879"

set newMacAddress to {}
repeat with i from 1 to 11 by 2
	set the end of newMacAddress to text i thru (i + 1) of macAddress & ":"
end repeat

set newMacAddress to text 1 thru -2 of (newMacAddress as text) --> "64:16:7F:59:F8:79"

Thank you, but how do I get it to replace selected text?

To answer your question, you need to provide more information as to the source of the MAC addresses (perhaps an application or document) and the destination of the modified MAC addresses. Also, just some idea as to how you expect this to work.

The source would be the text currently selected.

The application that contains the selected text can make a difference in how the script is written. The following is a generic script that works with many apps. It uses GUI scripting and, as a result, is a bit slow, but I successfully tested it with TextEdit, Script Editor, FSNotes, and the Safari address bar.

tell application "System Events"
	set activeApp to name of first process whose frontmost is true
	tell process activeApp to keystroke "c" using {command down}
end tell

delay 0.2

set macAddress to (the clipboard as text)

if (count macAddress) = 12 then
	set newMacAddress to {}
	repeat with i from 1 to 11 by 2
		set the end of newMacAddress to text i thru (i + 1) of macAddress & ":"
	end repeat
	set newMacAddress to text 1 thru -2 of (newMacAddress as text)
else
	display dialog "The selected text does not contain 12 characters" buttons {"OK"} cancel button 1 default button 1 with icon stop
end if

set the clipboard to newMacAddress

tell application "System Events"
	tell process activeApp to keystroke "v" using {command down}
end tell