2011-09-11 351 views
3

我想使用AppleScript查找和替換選定文檔中的文本。我想要替換的文本總是相同的,所以我想用該字符串設置一些預定義的變量,在所選文檔中搜索該字符串,並將其替換爲另一個預定義的字符串。我想重複這個查找和替換過程大約4次(每次查找不同的字符串變量)該文檔。一旦完成,我想自動保存修改過的文檔。AppleScript查找和替換選定文件中的字符串集

有人可以爲我提供簡單的腳本來做到這一點嗎?這是我迄今爲止......

tell application "Finder" 
    set theFile to (open for access (choose file with prompt "Select a file to read:")) 
    set txt to (read theFile for (get theFile)) 
end tell 

on replaceText(find, replace, subject) 
set prevTIDs to text item delimiters of AppleScript 
set text item delimiters of AppleScript to find 
set subject to text items of subject 

set text item delimiters of AppleScript to replace 
set subject to "" & subject 
set text item delimiters of AppleScript to prevTIDs 

return subject 
end replaceText 

get replaceText("lorem", "ipsum", txt) 

問題是它沒有讀取文件的所有內容(.html)。它只是讀一Lorem存有款 「存有存有悲坐阿梅德,consectetur adipisicing ELIT,sed的做eius」 我試圖在(獲得theFile)使用EOF但並不工作要麼

回答

3

是啊。 :)

set the search_document to (choose file of type "TEXT") 
replaceText("whatever you want to search for", "whatever you want to replace with", search_document) 

on replaceText(search_string, replacement_text, this_document) 
    tell application "TextEdit" 
     open this_document 
     set AppleScript's text item delimiters to the search_string 
     set this_text to the text of the front document as list 
     set AppleScript's text item delimiters to the replacement_text 
     set the text of the front document to (this_text as string) 
     close this_document saving yes 
    end tell 
end replaceText 

關於此腳本的快速預警,雖然。如果你是用含有該字符串文檔中的文字two一詞取代one的每一次出現......

If someone added one plus one, what would be the result? 

...這是你的結果...

If sometwo added two plus two, what would be the result? 

其他除此之外,沒有什麼可擔心的。

快樂編碼! :)

+0

乾杯!我已經添加了一個腳本來顯示我的進度。你能幫我嗎?我修改了原帖以顯示我現在遇到的問題。 – Kerron

+0

@Kerron羊皮紙請嘗試使用(應用程序「TextEdit」的路徑)'打開this_document' – fireshadow52

+0

nope。仍然無法取代文本並保存文件。 – Kerron

相關問題