replace - AppleScript 用于查找和替换选定文件中的字符串集

标签 replace find applescript

我想使用 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/

相关文章:

javascript - 浏览器是否处理 dom 更改匹配?

sqlite - 使用find,sqlite3和xargs组合许多小的sqlite数据库文件

c++ - 在 List c++ 中查找元素

javascript - 替换多个包含 $ 符号的字符串

c# - 查找并用新行替换 ASCII 字符

c++ - 在 C++ 中有替代的 str.find 吗?

objective-c - 将 NSURL 转换为 AppleScript 文件路径

vim - 如何更新applescript以在iTerm3中的vim中打开txt文件

applescript - 如何使用 AppleScript 来计时程序执行时间

PHP - 删除字符串中 HTML 标签的效果 - 但也显示它们?