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

求助:修改SVG颜色的AppleScript报路径不存在错误

问题分析与解决方案

错误原因

你遇到的sh: Macintosh: No such file or directory错误,核心原因是AppleScript文件对象未转换为Shell可识别的路径格式:

  • choose file返回的是HFS格式路径(以冒号分隔,如Macintosh HD:Users:xxx:Desktop:test:bubble.svg),而Shell命令(如sed)只支持POSIX格式路径(以斜杠分隔,如/Users/xxx/Desktop/test/bubble.svg)。
  • 未对路径进行引号包裹,若路径含空格会导致Shell解析错误。

此外你的代码还存在两个逻辑问题:

  1. 向原文件追加内容而非覆盖(starting at eof会把修改后的内容加在文件末尾);
  2. 最终复制到剪贴板的是颜色值而非修改后的SVG内容。

修正后的完整代码

on run
    try
        -- 弹出输入框获取新HEX颜色
        set theHex to text returned of (display dialog "Enter the new HEX color for the icon:" default answer "#FFFFFF")
        
        -- 选择目标SVG文件
        set theFile to (choose file with prompt "Select the SVG file to modify:")
        
        -- 将AppleScript文件对象转换为Shell可识别的POSIX路径并转义特殊字符
        set posixPath to quoted form of POSIX path of theFile
        
        -- 使用sed替换SVG中的#000000为新颜色,获取修改后的内容
        set modifiedSVG to do shell script "sed 's/#000000/" & theHex & "/g' " & posixPath
        
        -- (可选)覆盖原文件内容(不需要修改原文件可删除这段)
        set fileRef to open for access theFile with write permission
        set eof of fileRef to 0 -- 先清空原文件
        write modifiedSVG to fileRef
        close access fileRef
        
        -- 将修改后的SVG内容复制到剪贴板
        set the clipboard to modifiedSVG
        
        display dialog "SVG color updated and copied to clipboard!" buttons {"OK"} default button 1
    on error errMsg number errNum
        display dialog "Error: " & errMsg & " (" & errNum & ")" buttons {"OK"} default button 1 with icon stop
        -- 异常时确保文件句柄关闭
        if errNum is not -128 then -- 排除用户主动取消的情况
            try
                close access theFile
            end try
        end if
    end try
end run

关键修复点说明

  1. 路径格式转换:

    • POSIX path of theFile:将HFS路径转为Shell兼容的POSIX路径;
    • quoted form of:自动转义路径中的空格、特殊字符,避免Shell解析错误。
  2. 文件写入逻辑修正:

    • set eof of fileRef to 0:清空原文件内容,再写入修改后的SVG,实现覆盖而非追加。
  3. 剪贴板内容修正:

    • 将set the clipboard to theHex改为set the clipboard to modifiedSVG,确保复制的是修改后的完整SVG内容。
  4. 错误处理:

    • 新增try/on error块,捕获异常并提示用户,同时确保文件句柄在异常时正常关闭,避免文件锁定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:11:06