Automate moving and renaming files

I have files nested within multiple sub-folders. I want to move these files, one folder up the folder structure and rename the files as per its new parent folder. I will need this to be automated with a script.

Example logic

  1. Find Root folder
  2. Get contents of Subfolder of Subfolder files.
  3. Move files to its Parent folder (aka ‘Attachments’ folder)
  4. Rename files to with its current Parent folder name.
  5. Delete empty Subfolder
  6. Loop above action of Root folder folders until complete.

Example folder structure

Desired Result

DANGEROUS SCRIPT! MAKE FIRST BACKUP OF ROOT FOLDER (HERE IS “APPLICATIONS” FOLDER):


set rootFolder to path to applications folder
tell application "Finder" to set theSubfolders to every folder of rootFolder

repeat with theItem in theSubfolders
	tell application "Finder"
		set theSubfolder2 to folder 1 of theItem
		set theFile to file 1 of theSubfolder2
	end tell
	set name of theFile to (name of theItem)
	tell application "System Events"
		move theFile to theItem
		delete theSubfolder2
	end tell
end repeat