Batch removing part of filenames using Automator

applescriptautomatorfinder

I'm trying to create an Automator script that removes portion of a filename after a delimeter while preserving the extension.

Files are usually called like 1-cropped_DSC5888.jpg, 2-cropped_Whatsapp75.png etc. I want to remove everything after _ and keep only the part with number and '-cropped' so like: 1-cropped.jpg

I tried it with this script

on run {input, parameters}
try
    set AppleScript's text item delimiters to {"_"}
    set theFileNameList to {}
    repeat with thisItem in input
        set the end of theFileNameList to text item 2 of (thisItem as text)
    end repeat
    set AppleScript's text item delimiters to {}
    return theFileNameList
on error eStr number eNum
    display dialog eStr & " number " & eNum buttons {"OK"} ¬
        default button 1 with icon caution
    set AppleScript's text item delimiters to {}
    return
end try

end run

But this removes the part I want to keep and keeps the part I want to delete. Also it gives me just an output, but doesn't rename the actual files. Any help with this, please?

Best Answer

All you are doing is returning a list of the last part of the names (if there is more than one delimiter character, the second part) to the next action.

Text item delimiters aren't really needed if you are just using the first occurrence of a character, so you can do something like:

on run {input, parameters}
    set output to {}
    repeat with anItem in input
        set {theFolder, oldName, extension} to getNamePieces from anItem
        try
            set here to offset of "_" in oldName
            set newName to text 1 thru (here - 1) of oldName
            tell application "Finder" to set name of anItem to (newName & extension)
            set end of output to (theFolder & newName & extension) as alias
        on error errmess -- don't rename if error (delimiter not found, duplicate file, etc)
            log errmess
            set end of output to anItem as alias
        end try
    end repeat
    return output -- for next action
end run

to getNamePieces from someItem
    tell application "System Events" to tell disk item (someItem as text)
        set |container| to path of container
        set {|name|, extension} to {name, name extension}
    end tell
    if extension is not "" then
        set |name| to text 1 thru -((count extension) + 2) of |name| -- just the name part
        set extension to "." & extension
    end if
    return {container, |name|, extension}
end getNamePieces