Automator script to paste each word on clipboard followed by tab key
How can I create an Automator script to split the contents of my clipboard on space, and then paste each word followed by the tab key?
You can use a Run AppleScript action in an Automator workflow to accomplish this.
Example AppleScript code:
set cbText to (the clipboard)
set AppleScript's text item delimiters to space
set cbTextAsList to text items of cbText
set AppleScript's text item delimiters to {}
repeat with aWord in cbTextAsList
tell application "System Events"
keystroke aWord
delay 0.05
key code 48 -- # Tab key
delay 0.05
end tell
end repeat
Notes:
- The example AppleScript code was tested in Script Editor under macOS Catalina.
- Whatever the words are to be typed into must be frontmost as this is required for UI Scripting code, which is what System Events is doing.
- As coded, it assume focus is already in the first text box the first word is to be typed when the script is triggered.
If you really want to paste the words instead of typing, then use the following example AppleScript code instead:
set cbText to (the clipboard)
set AppleScript's text item delimiters to space
set cbTextAsList to text items of cbText
set AppleScript's text item delimiters to {}
repeat with aWord in cbTextAsList
set the clipboard to ""
delay 0.05
set the clipboard to aWord
delay 0.05
tell application "System Events"
keystroke "v" using command down
delay 0.05
key code 48 -- # Tab key
delay 0.05
end tell
end repeat
Note: The example AppleScript code is just that and sans any included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5
, with the value of the delay set appropriately.