在OS X中使用AppleScript编辑剪贴板内容

Tab*_*asa 5 macos clipboard applescript replace

我正在将许多源代码从不同的项目复制到其他项目,而我总是必须更改相同的术语。是否可以使用检查剪贴板文本内容并替换多个关键字的applescript?我是applescript的新手,所以我不知道applescript有多么强大...

Mic*_*ber 5

可以使用get clipboardset clipboard和文本项定界符。

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
Run Code Online (Sandbox Code Playgroud)

对于更复杂的文本操作,我只需要调用shell脚本即可。以上内容变为:

do shell script "pbpaste | sed 's/this text/that text/g' | pbcopy"
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢您的快速回复!该脚本可以正常工作,但是我还有很多其他问题:如何保持字符串格式(当前以纯文本形式返回,删除了每种格式)。我也无法让脚本替换多个字符串并在后台连续运行?我试图在“空闲”和“结束空闲”之间设置“获取/设置剪贴板...”代码,但是它在我启动应用程序时才第一次起作用(我将其保存为应用程序并检查保持打开状态) (2认同)