PDA

View Full Version : Automator + AppleScipt for text find&replace




tgelston
Mar 10, 2009, 02:32 PM
I have the dream of having an automator and Applescript combo that takes text from the clipboard, runs a little find and replace and puts the modified text back on the clipboard. Specifically I want to convert copied HTML links to BBCode.



I found the following AppleScript


(*
searchReplaceText(searchTerm, replaceTerm, theText)
Replaces a string found in a text by another string.
This handle supports lists of search/replace terms.

Parameters:
searchTerm: the text to search for
replaceTerm: the text to use as replacement
theText: the text to search/replace

Examples:
searchReplaceText("foo", "bar", "You are a foo") --> "You are a bar"
searchReplaceText({"foo", " a "}, {"bar", " one "}, "You are a foo") --> "You are one bar"
*)

to searchReplaceText({"foo", " a "}, {"bar", " one "}, "You are a foo")
set searchTerm to searchTerm as list
set replaceTerm to replaceTerm as list
set theText to theText as text

set oldTID to AppleScript's text item delimiters
repeat with i from 1 to count searchTerm
set AppleScript's text item delimiters to searchTerm's item i
set theText to theText's text items
set AppleScript's text item delimiters to replaceTerm's item i
set theText to theText as text
end repeat
set AppleScript's text item delimiters to oldTID

return theText
end searchReplaceText


I can use Automator to grab the contents of the clipboard but I can't seem to make the above script do anything AND I have no idea how to pass it the text from the clipboard.

This isn't do or die important but it has become something that is stuck in my brain and I would like to figure it out.

Thanks,
Tobias



angelwatt
Mar 10, 2009, 03:29 PM
Check out this write-up for transferring contents to/from the clipboard (http://www.macosxhints.com/article.php?story=20051011121117528).