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

如何用AppleScript在文件中将无格式数字日期替换为指定格式日期

修改AppleScript实现日期格式自动替换

需求:将文件中类似230629_的6位数字日期前缀,替换为当日的DDMMYYYY_格式日期(例如将230629_TO_SS_PACKAGE_001改为29062023_TO_SS_PACKAGE_001)。以下是修改后的AppleScript代码:

-- 生成当日的DDMMYYYY_格式日期字符串
set currentDate to current date
set dayStr to text -2 thru -1 of ("0" & day of currentDate) -- 补零确保两位数
set monthStr to text -2 thru -1 of ("0" & (month of currentDate as integer)) -- 月份转数字并补零
set yearStr to year of currentDate as string
set stringToReplace to dayStr & monthStr & yearStr & "_"

-- 选择目标文件
set theFile to choose file
set theContent to read theFile as «class utf8»

-- 使用正则表达式匹配并替换6位数字加下划线的日期前缀
set theContent to my replaceRegEx(theContent, "\\d{6}_", stringToReplace)

-- 写入修改后的内容回文件
try
    set fd to open for access theFile with write permission
    set eof of fd to 0
    write theContent to fd as «class utf8»
    close access fd
on error
    close access theFile
end try

-- 正则替换处理函数
on replaceRegEx(inputText, searchPattern, replaceWith)
    set inputNSString to current application's NSString's stringWithString:inputText
    set regex to current application's NSRegularExpression's regularExpressionWithPattern:searchPattern options:0 |error|:(missing value)
    set outputNSString to regex's stringByReplacingMatchesInString:inputText options:0 range:{location:0, length:inputNSString's length} withTemplate:replaceWith
    return outputNSString as string
end replaceRegEx

关键修改说明:

  • 日期生成:通过current date获取当日日期,对日、月份补零确保两位数格式,拼接成DDMMYYYY_的目标字符串。
  • 正则匹配:新增replaceRegEx函数,调用Cocoa框架的NSRegularExpression,匹配所有符合\d{6}_(6位数字加下划线)的字符串,统一替换为当日日期。
  • 保留安全读写逻辑:沿用原有脚本中可靠的文件读写及错误处理部分,避免文件损坏风险。

内容的提问来源于stack exchange,提问作者Star S.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 03:32:09