【问题标题】:AppleScript to append date to fileAppleScript 将日期附加到文件
【发布时间】:2021-09-28 03:02:22
【问题描述】:

我最近能够在 Automator 中创建一个拖放脚本,它允许我压缩和命名一个文件,然后自动应用日期 (DDMMYY),但现在它默认为 (DDMMYYYY),我无法更改它。我搜索了一个解决方案,但没有任何效果,因为这需要位于文件名的末尾。

有谁知道我做错了什么,或者有没有人有一个可以帮助我的实际脚本?我发现的所有内容只有在日期位于文件名开头而不是结尾(但在扩展名之前)时才有效。

【问题讨论】:

  • 我尝试发布我的工作流程的图像,但不允许。我对此也很陌生,所以我没有任何代码,只需从 Automator 拖放即可。它让我发布一个链接,这样就可以了)。我在大苏尔

标签: macos applescript rename automator


【解决方案1】:

由于您没有提供任何代码,我无法猜测您如何命名文件,但获取 DDMMYY 的方法是使用带有 do shell script 命令的 shell:

tell application "Finder"
    set theFile to (choose file)
    set theName to name of theFile
    set name of theFile to theName & "_" & (do shell script "date +%d%m%y") & ".xxx"
end tell

这并没有去掉原始文件的文件扩展名。为此,您必须使用以下内容:

tell application "Finder"
    set theFile to (choose file)
    set theName to name of theFile
    set periodIndex to offset of "." in theName
    set theName to text 1 thru (periodIndex - 1) of theName
    set name of theFile to theName & "_" & (do shell script "date +%d%m%y") & ".xxx"
end tell

负责删除文件扩展名的代码来自this post

您可以通过将所需符号放在下一个% 之前来添加您喜欢的标点符号。所以date +%d.%m.%y 是可能的并且提高了可读性。

【讨论】:

  • 对不起。不太擅长这个。所以我们的标准文件命名约定是 filename_DDMMYY.xxx
  • file (choose file) - 即使它有效 - 也是语法错误。 choose file 返回别名说明符,因此关键字 file 是双重引用。删除file
  • @vadian 我正在重写脚本以适应 OP 留下的评论。
  • 如果文件名为 Paris.LaCroix.men.zip 呢?
  • @CJK 我很少看到有人将多个句点放在一个文件名中。如果您知道解决此问题的方法,请随时编辑我的答案
【解决方案2】:

您可以在 Run AppleScript 操作中使用此 AppleScript,它会重命名存档并在文件扩展名之前插入日期

on run {input, parameters}
    set thePath to POSIX path of (item 1 of input)
    set currentDate to do shell script "date +%d%m%y"
    set newPath to text 1 thru -5 of thePath & "_" & currentDate & ".zip"
    do shell script "mv " & quoted form of thePath & space & quoted form of newPath
    return {POSIX file newPath as alias}
end run

【讨论】:

  • @Steven Cheak,请注意,按照目前的编码,它有可能在没有警告的情况下覆盖现有的文件。为确保不覆盖文件,请将"mv " 更改为:"mv -n "
  • 有趣。虽然这包含很多 AppleScript 语法,但除了 set newPath to … 行之外,它都是填充,是什么让你选择将本质上是一个 shell 脚本的东西包装在 AppleScript 中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-20
  • 1970-01-01
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
  • 2021-08-26
  • 2014-07-28
相关资源
最近更新 更多