示例 AppleScript 代码,如下所示,在 macOS Catalina 下的 Script Editor 中进行了测试 将 系统偏好设置 中的 语言和地区 设置设置为 英语(美国)- 主要 并且为我工作没有问题 1.
-
1 假设 系统偏好设置 > 安全和隐私 > 隐私中的必要和适当的设置已设置/根据需要解决。
示例 AppleScript 代码:
set textToFindList to {"unripe apple", "unripe kiwi", "unripe banana"}
set textToReplaceWithList to {"ripe apple", "ripe kiwi", "ripe banana"}
if (length of textToFindList) is not equal to ¬
(length of textToReplaceWithList) then return
set theFile to choose file
-- tell application "Finder" to duplicate file theFile with exact copy
set theText to read theFile as «class utf8»
repeat with i from 1 to length of textToFindList
set theText to my findAndReplaceInText(theText, ¬
item i of textToFindList, ¬
item i of textToReplaceWithList)
end repeat
my writeToFile(theText, theFile, true)
-- # Handlers #
on findAndReplaceInText(theText, theSearchString, theReplacementString)
--considering case
set AppleScript's text item delimiters to theSearchString
set theTextItems to every text item of theText
set AppleScript's text item delimiters to theReplacementString
set theText to theTextItems as string
set AppleScript's text item delimiters to ""
return theText
--end considering
end findAndReplaceInText
on writeToFile(theText, theFile, overwriteExistingContent)
try
set theFile to theFile as string
if theFile contains "/" then
set theOpenedFile to open for access theFile with write permission
else
set theOpenedFile to open for access file theFile with write permission
end if
if overwriteExistingContent is true then set eof of theOpenedFile to 0
write theText to theOpenedFile starting at eof
close access theOpenedFile
return true
on error
try
close access file theFile
end try
return false
end try
end writeToFile
注意事项:
writeToFile(theText, theFile, overwriteExistingContent) handler 是一个稍微修改的 handler,来自:Reading and Writing Files
链接的 Apple 支持文档中的 处理程序 已修改为处理 POSIX 和 HFS+ 文件路径.
findAndReplaceInText(theText, theSearchString, theReplacementString) 处理程序 if from 在字符串中查找和替换文本 from:Manipulating Text
如果您需要区分大小写的查找/替换,请取消注释 on findAndReplaceInText(theText, theSearchString, theReplacementString) handler 中 code 的 --considering case 和 --end considering 行。
如果您要在编辑之前自动制作文件的备份副本,请从以下代码_行前面删除-- :
tell application "Finder" to duplicate file theFile with exact copy
注意:示例 AppleScript 代码 就是这样,没有任何包含的错误处理不包含任何适当的额外错误处理。用户有责任根据需要或需要添加任何错误处理。查看AppleScript Language Guide 中的try statement 和error statement。另请参阅Working with Errors。此外,在适当的情况下,可能需要在事件之间使用delay 命令,例如delay 0.5,延迟的值设置得当。