Up front, my skills with AppleScript are very basic. I have cobbled together a script that I thought would take and use the selection of the frontmost window and apply multiple search and replace actions using matched pair data. Thus finding tablespoon would trigger a replacement with tsp. I’ve put the script to gether using everything I could understand from this forum.
How can I get this to work?
– Clear the clipboard
set the clipboard to “”
– Get the selected text from the frontmost window
tell application “System Events”
set selectedText to (value of text area 1 of scroll area 1 of front window of application process “TextEdit”) as string
end tell
– Set the search and replace lists
set toFindList to {“teaspoon”, “tablespoon”, “ounce”, “fluidounce”, “cup”, “pint”, “quart”, “gallon”, “pound”, “gram”, “kilogram”, “liter”, “milliliter”, “teaspoons”, “tablespoons”, “ounces”, “fluidounces”, “cups”, “pints”, “quarts”, “gallons”, “pounds”, “grams”, “kilograms”, “liters”, “milliliters”}
set replaceWith to {“tsp”, “tbsp”, “oz”, “fl”, “oz”, “cup”, “pt”, “qt”, “gal”, “lb”, “g”, “kg”, “L”, “mL”, “tsp”, “tbsp”, “oz”, “fl”, “oz”, “cups”, “pts”, “qts”, “gals”, “lbs”, “g”, “kg”, “L”, “mL”}
– Perform the search and replace on the selected text
repeat with i from 1 to count of toFindList
set thisFind to item i of toFindList
set thisReplace to item i of replaceWith
set selectedText to my replaceText(“\b” & thisFind & “\b”, thisReplace, selectedText)
end repeat
– Set the modified text as the clipboard contents
set the clipboard to selectedText
– Paste the modified text back into the frontmost window
tell application “System Events”
keystroke “v” using {command down}
end tell
– Define a handler to replace text in a string
on replaceText(findText, replaceText, sourceText)
set theRegex to (“s/” & findText & “/” & replaceText & “/g”)
set escapedText to do shell script "echo " & quoted form of sourceText & " | sed -E " & quoted form of theRegex
return escapedText
end replaceText