macOS 利用 Shortcuts.app 在 Finder 中增加新增文件的功能
起源
从发帖求助后,自己细想想应该有工具可以往右键添加操作,不想下载新 App,检索对比 Automator.app 和 Shortcuts.app 后决定还是使用 Shortcuts.app 搭配 AppleScript 来实现我要的操作。
脚本
-- 辅助函数:去除字符串首尾的空格、制表符、换行等空白字符
on trimText(theString)
if theString is "" then return theString
-- 使用非保留字的变量名:trimStart / trimEnd
set trimStart to 1
repeat while trimStart ≤ length of theString and character trimStart of theString is in {" ", tab, return, linefeed}
set trimStart to trimStart + 1
end repeat
if trimStart > length of theString then return ""
set trimEnd to length of theString
repeat while trimEnd ≥ trimStart and character trimEnd of theString is in {" ", tab, return, linefeed}
set trimEnd to trimEnd - 1
end repeat
return text trimStart thru trimEnd of theString
end trimText
-- 获取 Finder 当前窗口的位置
tell application "Finder"
set currentPath to insertion location as alias
end tell
-- 弹出对话框,提示用户输入文件名,默认为“Untitled.txt”
set defaultName to "Untitled.txt"
set userInput to text returned of (display dialog "请输入新文件的名称:" default answer defaultName with title "创建新文件")
-- 清理用户输入:去除首尾空白
set fileName to my trimText(userInput)
-- 如果用户什么都没输(或只输空格),则使用默认文件名
if fileName is "" then set fileName to defaultName
-- 智能处理扩展名:
-- 情况1:文件名中不含“.”,或者以“.”开头(如“.gitignore”),则添加 .txt
-- 情况2:文件名以“.”结尾(如“笔记.”),则补全为“.txt”
if fileName does not contain "." or fileName begins with "." then
set fileName to fileName & ".txt"
else if last character of fileName is "." then
set fileName to fileName & "txt"
end if
-- 检查是否已存在同名文件,若存在则自动添加编号(如“文件 1.txt”)
tell application "Finder"
set baseName to fileName
set counter to 1
-- 从文件名末尾查找第一个“.”,正确分离主文件名和扩展名
set revChars to reverse of characters of fileName as string
set dotIndex to offset of "." in revChars
if dotIndex = 0 then
-- 理论上不会发生(前面已处理无扩展名情况),但保留安全兜底
set namePart to fileName
set fileExt to ""
else
-- 提取扩展名(如“txt”)和主文件名(如“报告”)
set fileExt to reverse of (characters 1 through (dotIndex - 1) of revChars) as string
set namePart to text 1 thru -(dotIndex + 1) of fileName
end if
-- 循环检查文件是否存在,若存在则生成带编号的新文件名
set fileName to baseName
repeat while (exists file ((currentPath as text) & fileName))
if fileExt is "" then
set fileName to namePart & " " & counter
else
set fileName to namePart & " " & counter & "." & fileExt
end if
set counter to counter + 1
end repeat
-- 在当前目录创建新文件,并在 Finder 中高亮显示
set newFile to make new file at currentPath with properties {name:fileName}
reveal newFile
end tell
AIGC 声明:本脚部分函数由 通义千问 辅助创造,本人已验证其生成内容的真实性和有效性
使用方法
我也是第一次接触 AppleScript ,考虑可能有其他佬友也未接触使用过,特贴出使用方法
- 打开
Shortcuts.app - 如果你是首次使用,请按
⌘ + ,打开设置中的高级-允许使用脚本 - 新建快捷指令
- 设置基本信息
- 添加 AppleScript
- 在 Finder 中使用
参考文献
AppleScript 开发文档
AppleScript 入门:探索 macOS 自动化 - 少数派
如果有帮到你,还请给我投两个 LDC 吧!
或者请我喝杯咖啡
都不想的话请点个免费的也好





