shell 使用AppleScript从文件名称中移除尾随的日期时间和数字

os8fio9y  于 2022-11-16  发布在  Shell
关注(0)|答案(1)|浏览(129)

我不得不调整很多文件,以删除它们的最后一部分:
从这里:
108595-1121_gemd_u65_stpetenowopen_em_f_2021-12-03T161809.511773.zip
对此:
108595-1121_gemd_u65_stpetenowopen_em_f.zip
它总是24个字符,需要剥离,总是有一个下划线的开始。其余的是随机数字和字符。我发现下面的代码删除数字,但我需要字符。
我的目标是把它放在一个automator脚本和其他一些进程中,但是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
qvk1mo1f

qvk1mo1f1#

这里不需要使用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行通过在字符'_'处剪切name字符串,将name-string 拆分为字符串部分的 list
  • 第7行删除该 list 中的最后一项(即最后一个'_'之后的所有内容)
  • 第8行反转了这个过程,通过使用'_'将缩短的文本项 list 组合成一个 string
  • 其余部分将TID值重置为其原始状态,向字符串添加扩展名,并更改文件名

相关问题