如何移除macOS子文件夹及文件名称中的(1)后缀?
批量移除文件/文件夹名称中的(N)后缀
原AppleScript的问题
原脚本存在几个关键缺陷:
- 仅支持PDF文件,无法处理文件夹和其他类型文件
- 文件名处理逻辑错误:保留了
(1)后缀,还重复添加.pdf扩展名 - 不递归处理子文件夹,只能处理选定文件夹下的一级文件
修正后的AppleScript(支持全类型+递归处理)
以下脚本可以递归处理选定文件夹内所有文件和子文件夹,移除名称末尾所有形如(数字)的后缀(包括多次追加的情况,比如Folder (1) (1)会被修正为Folder):
-- 定义要匹配的后缀模式:末尾的 (数字) set suffixPattern to "\\s\\(\\d+\\)$" -- 选择要处理的根文件夹 set sourceFolder to choose folder default location (path to home folder) -- 递归处理文件夹的函数 on processFolder(folderObj) tell application "Finder" -- 获取当前文件夹下的所有文件和子文件夹 set allItems to every item in folderObj -- 先处理文件,再处理子文件夹 repeat with itemObj in allItems if class of itemObj is file then set oldName to name of itemObj set newName to my removeSuffix(oldName) if newName ≠ oldName then try set name of itemObj to newName on error errMsg display dialog "无法重命名文件:" & oldName & return & errMsg buttons {"跳过", "取消"} default button 1 end try end if else if class of itemObj is folder then set oldName to name of itemObj set newName to my removeSuffix(oldName) if newName ≠ oldName then try set name of itemObj to newName on error errMsg display dialog "无法重命名文件夹:" & oldName & return & errMsg buttons {"跳过", "取消"} default button 1 end try end if -- 递归处理子文件夹 my processFolder(itemObj) end if end repeat end tell end processFolder -- 移除末尾所有(N)后缀的函数 on removeSuffix(oldName) set tempName to oldName -- 循环移除所有末尾的 (数字) 后缀 repeat while tempName matches suffixPattern -- 找到最后一个空格的位置,截取之前的部分 set spacePos to offset of " " in reverse of tempName if spacePos > 0 then set tempName to text 1 thru ((length of tempName) - spacePos) of tempName else exit repeat end if end repeat return tempName end removeSuffix -- 启动处理 my processFolder(sourceFolder) display dialog "处理完成!" buttons {"确定"} default button 1
使用方法
- 打开Mac自带的「脚本编辑器」(在Launchpad的「其他」文件夹里)
- 将上述代码粘贴到编辑器中
- 点击工具栏的「运行」按钮(▶️)
- 在弹出的窗口中选择需要处理的根文件夹,等待脚本执行完成
注意事项
- 强烈建议先备份目标文件夹,避免意外情况导致文件丢失
- 脚本会处理隐藏文件,如果需要跳过隐藏文件,可以在获取
allItems时添加过滤条件 - 如果遇到重名文件/文件夹,脚本会弹出提示,可选择跳过或取消操作
内容的提问来源于stack exchange,提问作者Charles Stricklin
相关产品推荐
相关产品推荐

