使用 AppleScript 在文本文件中查找和替换

2024-01-29

我正在尝试编写一个将通过启动代理运行的苹果脚本。该脚本需要做的是编辑用户首选项 plist 文件,以便默认保存位置特定于该用户。我知道这可以通过将“~/documents”设置为模板 plist 中的位置来完成。但例如 Premier Pro 还需要将临时文件写入本地驱动器。为简单起见,我希望每个用户根据他们的用户名将它们放置在某个位置。仅当首次登录时刚刚从模板创建本地配置文件时才需要运行此脚本。

我首先使用本网站上找到的一些示例代码,然后在下面进行一个简单的测试。此测试应编辑 txt 文件并将一个单词替换为另一个单词。该脚本当前无法运行。测试时,它会在 TextEdit 中打开 test.txt,但不会执行任何其他操作。也没有显示任何错误。

先感谢您

John.

replaceText("replace this", "replace with this", "/Volumes/USB_Drive/test.txt")


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

这是不需要文本编辑的版本。它将读取 utf-8 编码的文件,更新其内容并将其作为 utf-8 编码文本存储回文件中。我在写入文件时使用 try 块的原因是,如果另一个应用程序同时以读取权限打开该文件,则会出现错误。考虑的案例块可以包裹在将 ti 设置为 theContent 的每个文本项如果您想要搜索并替换区分大小写。当您替换字符串时,无需激活此功能,只需查找它即可。

set stringToFind to "replace that"
set stringToReplace to "with this"
set theFile to choose file
set theContent to read theFile as «class utf8»
set {oldTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, stringToFind}
set ti to every text item of theContent
set AppleScript's text item delimiters to stringToReplace
set newContent to ti as string
set AppleScript's text item delimiters to oldTID
try
    set fd to open for access theFile with write permission
    set eof of fd to 0
    write newContent to fd as «class utf8»
    close access fd
on error
    close access theFile
end try
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 AppleScript 在文本文件中查找和替换 的相关文章

随机推荐