MacOS – Remove folder name from file name based on existing Apple Script

applescriptfilefinderfoldersmacos

so I have this apple script here that I used to insert the folder name into the front of all the files in the folder. The script is able to run through every single folder and target all the files and proved to be very useful

    set the_folder to (choose folder)
renamefilesinside(the_folder)

on renamefilesinside(next_folder)
    tell application "Finder"
        set folder_name to name of next_folder & " "
        set folder_contents to every item of next_folder
        repeat with each_item in folder_contents
            if kind of each_item is "folder" then
                my renamefilesinside(each_item)
            else
                set name of each_item to folder_name & " " & name of each_item
            end if
        end repeat
    end tell
end renamefilesinside

Source: https://discussions.apple.com/thread/275167

However, now I have removed a part of the folder names and would like a subtractive effect to be applied to the files, so the script will take the files, look at the parent folder's name, and remove the shared characters.

Unfortunately I know very little about apple scripts so I'm hoping this is an easy adjustment that someone here can make.

Thanks for any help you can give!

Best Answer

You can get the file name, then set the text item delimiter to the containing folder name, then put the text items of the file name into a list, which will ignore the delimiter (the folder name), then reset the text item delimiter to "" empty and coerce the name to a string. This is a VERY common Applescript trick.

set the_folder to (choose folder)
renamefilesinside(the_folder)

on renamefilesinside(next_folder)
    tell application "Finder"
        set folder_name to name of next_folder
        set folder_contents to every item of next_folder
        repeat with each_item in folder_contents
            if kind of each_item is "folder" then
                my renamefilesinside(each_item)
            else
                set n to name of each_item
                set AppleScript's text item delimiters to folder_name
                set n to text items of n
                set AppleScript's text item delimiters to ""
                set n to n as string
                set name of each_item to n
            end if
        end repeat
    end tell
end renamefilesinside