简体   繁体   中英

Remove last X characters from a file with AppleScript

I have to adjust a lot of files to remove the last part of them:

From this:
108595-1121_gemd_u65_stpetenowopen_em_f_2021-12-03T161809.511773.zip

To this:
108595-1121_gemd_u65_stpetenowopen_em_f.zip

It's always 24 characters that need to be stripped and there is always an underscore at the beginning. The rest is random numbers and characters. I found code below to remove numbers, but I need characters.

My goal is to put this in an automator script with some other processes, but the Renamer in Automator isn't robust enough.

How can I have it strip X-number of characters? My google-fu has failed me.

(:

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

No need to use do shell script here, which just confuses the issue. Since your names are underscore-delimited, just use AppleScript's 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

What this does, in words:

  • lines 4 and 5 first save the current text item delimiter (TID) value and then set it to '_'
  • line 6 breaks the name- string into a list of string parts by cutting the name string at the character '_'
  • line 7 drops the last item in that list (which is everything after the last '_')
  • line 8 reverses the process, combining the shortened list of text items into a single string by joining them with '_'
  • The remainder resets the TID value to its original state, adds the extension to the string, and changes the file name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM