2011-03-24 53 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的原始代碼的榮譽。我對編碼幾乎一無所知。我只是嘗試了這種修改工作。