我想使用 AppleScript 查找并替换所选文档中的文本。我想要替换的文本始终是相同的,因此我想使用该字符串设置一些预定义变量,在所选文档中搜索该字符串,然后将其替换为另一个预定义字符串。我想为该文档重复此查找和替换过程大约 4 次(每次查找不同的字符串变量)。完成此操作后,我想自动保存修改后的文档。
有人可以为我提供简单的脚本来执行此操作吗?这是我到目前为止所拥有的...
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 ipsum 段落的它只是阅读 “ipsum ipsum dolor sat amet,consectetur adipisicing elit,sed do eius” 我尝试在(获取文件)中使用 eof,但这也不起作用
最佳答案
是的。 :)
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
不过,关于此脚本的快速警告。如果您要在包含此字符串的文档中将每次出现的单词 one
替换为单词 two
...
If someone added one plus one, what would be the result?
...这将是你的结果...
If sometwo added two plus two, what would be the result?
除此之外,没有什么可担心的。
编码愉快! :)
关于replace - AppleScript 用于查找和替换选定文件中的字符串集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7378370/