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

7

我经常从不同的项目中复制大量源代码到其他项目中,但总是需要更改相同的术语。是否可以使用一种 AppleScript,检查剪贴板的文本内容并替换多个关键字?我对 AppleScript 还很陌生,不知道它可以有多强大...

2个回答

6
这可以通过使用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

如果需要更复杂的文本操作,我会调用一个 shell 脚本。上面的代码可以改写成:

do shell script "pbpaste | sed 's/this text/that text/g' | pbcopy"

2
非常感谢您的快速回复!脚本工作得很好,但我还有一堆其他问题:如何保持字符串格式(当前它返回为纯文本,所有格式都被删除)?我也无法让脚本替换多个字符串并在后台持续运行?我尝试在“on idle”和“end idle”之间设置“get/set clipboard...”代码,但它只能在我第一次启动应用程序时工作(我将其保存为应用程序并检查了“保持打开”)。 - TabulaRasa

3

我不确定我是否理解了您想要做什么。我认为您想要替换剪贴板内容中的多个字符串,例如:"PS3在沃尔玛售价200美元"变为"XBox在沃尔玛售价180美元"。以下代码可以实现此目的:

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)

感谢Michael J. Barber提供的原始代码。我对编程几乎一无所知,只是尝试了这个修改,它起作用了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接