You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AppleScript中给路径末尾的文件名前添加.

AppleScript 实现文件名前置点隐藏的两种方案

方案1:使用文本定界符手动处理路径字符串

对应你提到的定界符用法,核心是通过text item delimiters拆分路径、提取文件名后加.再重组:

set originalPath to "/Users/username/Desktop/file.txt"
-- 保存原有的定界符,避免影响后续脚本运行
set oldDelimiters to AppleScript's text item delimiters
-- 设置定界符为路径分隔符/
set AppleScript's text item delimiters to "/"
-- 拆分路径为列表
set pathItems to text items of originalPath
-- 提取最后一项也就是文件名
set fileName to last item of pathItems
-- 排除已经是隐藏文件的情况,避免重复加.
if fileName does not start with "." then
    -- 给文件名加前缀.
    set last item of pathItems to "." & fileName
    -- 重组路径
    set modifiedPath to pathItems as text
end if
-- 恢复原来的定界符
set AppleScript's text item delimiters to oldDelimiters

-- 输出结果,需要实际修改文件的话可以配合后续文件操作命令使用
return modifiedPath

方案2:调用系统事件直接操作文件(更稳妥,不需要手动处理路径拆分)

如果你的输入是实际存在的文件,推荐用这种方法,避免路径拆分出现边界错误(比如路径末尾带/、文件名本身带特殊符号的情况):

set originalPath to POSIX file "/Users/username/Desktop/file.txt" as alias
tell application "System Events"
    set fileName to name of originalPath
    if fileName does not start with "." then
        set name of originalPath to "." & fileName
    end if
end tell

注意事项

  • 给文件名前置.后,Finder默认会隐藏该文件,其他用户需要开启显示隐藏文件才能看到
  • 修改系统目录下的文件可能需要管理员权限,运行脚本时按需添加权限验证即可

内容的提问来源于stack exchange,提问作者hackedXD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 00:24:02