Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit clipboard content with applescript in os x

I'm copying a lot of source code from different projects to others and I always have to change the same terms. Is it possible to use an applescript which checks the text-content of the clipboard and replaces several keyword? I'm new to applescript so I'm not aware of how powerful applescript can be...

like image 340
TabulaRasa Avatar asked Mar 24 '11 11:03

TabulaRasa


2 Answers

This is possible using get clipboard, set clipboard, and the text item delimiters.

get the clipboard
set the clipboard to (replacement of "this text" by "that text" for the result)

on replacement of oldDelim by newDelim for sourceString
    set oldTIDs to text item delimiters of AppleScript
    set text item delimiters of AppleScript to oldDelim
    set strtoks to text items of sourceString
    set text item delimiters of AppleScript to newDelim
    set joinedString to strtoks as string
    set text item delimiters of AppleScript to oldTIDs
    joinedString
end replacement

For more sophisticated text manipulation, I'd just call out to a shell script. The above becomes:

do shell script "pbpaste | sed 's/this text/that text/g' | pbcopy"
like image 66
Michael J. Barber Avatar answered Nov 13 '22 19:11

Michael J. Barber


Not sure that I understood what you want to do. I reckon you want to replace multiple strings within the clipboard content, for example: "PS3 costs 200 dollars at Wallmart" to "XBox costs 180 dollars at Wallmart". The following code achieves this:

get the clipboard
set the clipboard to (replacement of "PS3" by "XBox" for the result)
on replacement of oldDelim by newDelim for sourceString
    set oldTIDs to text item delimiters of AppleScript
    set text item delimiters of AppleScript to oldDelim
    set strtoks to text items of sourceString
    set text item delimiters of AppleScript to newDelim
    set joinedString to strtoks as string
    set text item delimiters of AppleScript to oldTIDs
    joinedString
end replacement
get the clipboard
set the clipboard to (replacement of "200" by "180" for the result)

Kudos to Michael J. Barber for the original code. I know virtually nothing about coding. I just tried this modification it worked.

like image 43
Kalle Kantola Avatar answered Nov 13 '22 18:11

Kalle Kantola