2011-03-24 52 views
3

我将很多源代码从不同的项目拷贝到其他项目,而且我总是需要更改相同的条款。是否可以使用applescript来检查剪贴板的文本内容并替换几个关键字?我是新来的applescript,所以我不知道苹果的功能有多强大......使用os中的applescript编辑剪贴板内容x

回答

4

这是可能的使用get clipboard,set 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

非常感谢您的快速回复!该脚本工作正常,但我有一堆进一步的问题:我如何实现保持字符串格式(目前它以纯文本形式返回,每种格式都被删除)。我也无法让脚本替换多于一个字符串并在后台连续运行?我尝试在“闲置”和“结束闲置”之间设置“get/set剪贴板...”代码,但它只是在我启动应用程序时第一次运行(我将它保存为应用程序并且保持打开状态) – TabulaRasa 2011-03-24 12:49:38

2

不知道我明白你想要做什么。我想你想在剪贴板内容中替换多个字符串,例如:“PS3在Wallmart上花费200美元”到“XBox在Wallmart上花费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的原始代码的荣誉。我对编码几乎一无所知。我只是尝试了这种修改工作。