【问题标题】:Remove trailing date time and number from a filename with AppleScript使用 AppleScript 从文件名中删除尾随日期时间和数字
【发布时间】:2022-10-22 09:29:35
【问题描述】:

我必须调整很多文件以删除它们的最后一部分:

由此:
108595-1121_gemd_u65_stpetenowopen_em_f_2021-12-03T161809.511773.zip

对此:
108595-1121_gemd_u65_stpetenowopen_em_f.zip

总是需要删除 24 个字符,并且开头总是有一个下划线。其余的是随机数和字符。我在下面找到了删除数字的代码,但我需要字符。

我的目标是将其与其他一些进程一起放入自动机脚本中,但 Automator 中的重命名器不够健壮。

我怎样才能让它去掉 X 个字符?

on run {input, parameters}
    
    repeat with thisFile in input
        tell application "Finder"
            set {theName, theExtension} to {name, name extension} of thisFile
            if theExtension is in {missing value, ""} then
                set theExtension to ""
            else
                set theExtension to "." & theExtension
            end if
            set theName to text 1 thru -((count theExtension) + 1) of theName -- the name part
            set theName to (do shell script "echo " & quoted form of theName & " | sed 's/[0-9]*$//'") -- strip trailing numbers
            set name of thisFile to theName & theExtension
        end tell
    end repeat
    
    return input
end run

【问题讨论】:

    标签: shell applescript


    【解决方案1】:

    无需在这里使用do shell script,这只会混淆问题。由于您的名称是下划线分隔的,因此只需使用 AppleScript 的 text item delimiters

    repeat with thisFile in input
        tell application "Finder"
            set {theName, theExtension} to {name, name extension} of thisFile
            set tid to my text item delimiters
            set my text item delimiters to "_"
            set nameParts to text items of theName
            set revisedNameParts to items 1 through -2 of nameParts
            set newName to revisedNameParts as text
            set my text item delimiters to tid
            if theExtension is not in {missing value, ""} then 
                set newName to newName & "." & theExtension
            end if
            set name of thisFile to newName
        end tell
    end repeat
    
    return input
    

    这是做什么的,用一句话来说:

    • 第 4 行和第 5 行首先保存当前文本项分隔符 (TID) 值,然后将其设置为 '_'
    • 第 6 行打破了名称-细绳成一个列表通过在字符 '_' 处切割名称字符串来分割字符串部分
    • 第 7 行删除了最后一项列表(这是最后一个'_'之后的所有内容)
    • 第 8 行反转该过程,将缩短的列表将文本项合并为一个细绳用'_'加入他们
    • 其余部分将 TID 值重置为其原始状态,将扩展名添加到字符串,并更改文件名

    【讨论】:

    • 哇。那太完美了!你能解释一下它是如何选择它的吗?既然有几个下划线,它怎么知道不把它们都去掉呢?或者有多少个字符?
    • 我已经用解释修改了答案。
    • 你已经超越了自己!非常感谢你!!!!
    猜你喜欢
    • 2023-01-26
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    相关资源
    最近更新 更多