如何用AppleScript复制.gcode文件并添加original_前缀,保留原扩展名
修改后的AppleScript脚本
以下是调整后的脚本,副本文件名会以original_原文件名.gcode格式生成,保留原文件的.gcode扩展名:
use AppleScript version "2.4" -- Yosemite (10.10) 或更高版本 use framework "Foundation" use scripting additions on run -- 处理未拖放文件直接启动脚本的情况 set sourceFile to choose file of type {"gcode"} with prompt "选择.gcode文件" processFile(sourceFile) end run on processFile(sourceFile) -- 修改前先创建文件副本 set originalPath to POSIX path of (sourceFile as text) -- 拆分路径并生成带original_前缀的副本路径 set posixPath to current application's NSString's stringWithString:originalPath set parentDir to posixPath's stringByDeletingLastPathComponent() set fileName to posixPath's lastPathComponent() set baseName to fileName's stringByDeletingPathExtension() set ext to fileName's pathExtension() set newFileName to "original_" & baseName & "." & ext set copyPath to parentDir's stringByAppendingPathComponent:newFileName do shell script "cp " & quoted form of originalPath & " " & quoted form of (copyPath as text) set fileURL to sourceFile as «class furl» set fileDescriptor to open for access fileURL with write permission set theText to read fileDescriptor set {saveTID, text item delimiters} to {text item delimiters, {"; EXECUTABLE_BLOCK_START"}} try set {startBlock, remainder} to text items of theText set text item delimiters to {"; EXECUTABLE_BLOCK_END" & linefeed & linefeed} set endBlock to text item 2 of remainder set text item delimiters to saveTID set eof of fileDescriptor to 0 write (startBlock & endBlock) to fileDescriptor close access fileDescriptor on error e number n if n = -1728 then close access fileDescriptor else close access fileURL end if set text item delimiters to saveTID end try end processFile
核心修改说明
- 路径拆分逻辑:替换原脚本直接拼接
.copy后缀的方式,用Foundation框架的NSString方法精准处理路径:stringByDeletingLastPathComponent():提取文件所在的父目录lastPathComponent():获取完整的文件名(含扩展名)stringByDeletingPathExtension():分离出不带扩展名的文件名主体pathExtension():获取原文件的扩展名stringByAppendingPathComponent::将父目录、新文件名重新组合成完整路径
- 副本命名规则:新副本采用
original_原文件名.gcode格式,彻底替代原有的.copy后缀方案 - 注释本地化:将原脚本中的英文注释全部译为中文,方便理解维护
内容的提问来源于stack exchange,提问作者GilbertOOl
相关产品推荐
相关产品推荐

