how to set name of folder to string in middle of original file name

I have a script that works great as shown below, but if I change line 13 from…

set name of first_item to (text 1 thru 8 of theFile)

to

set name of first_item to (text 2 thru 8 of theFile)

the script breaks.

Can someone please tell me why and/or how I can solve this?

property dialog_timeout : 120 -- set the amount of time before dialogs auto-answer.

on adding folder items to this_folder after receiving dropped_items -- this_folder is an alias
	delay 5
	tell application "Finder"
		set this_folder_list to every folder of this_folder
		set this_file_list to every file of this_folder
		
		repeat with i in this_folder_list
			set first_item to item 1 of dropped_items -- name of entire path
			set theFile to (name of first_item)
			if kind of first_item is "folder" then
				set name of first_item to (text 1 thru 8 of theFile)
			end if
		end repeat
		
		set oldFiles to (every file of this_folder whose name starts with theFile)
		delete oldFiles
		
		delay 5
		
		repeat with i in this_folder_list
			set this_file_list to every file of i
			repeat with x in this_file_list
				set theFile to (name of x)
				set theFolderName to name of container of x
				set name of x to theFolderName & "_" & theFile
			end repeat
			
			set this_file_list_with_new_name to every file of i
			
			move this_file_list_with_new_name to this_folder
			
			delete i
			
			delay 5
			
			set unneededFiles to (every file of this_folder whose name extension is not in {"csv", "xml"})
			delete unneededFiles
			
		end repeat
	end tell
end adding folder items to

Hmm. All programming books are a reminder that novice users are the best inventors of the strangest mistakes.

Looking at your code, I can draw 2 conclusions:

  1. the length of the name of your first drag-and-drop folder = 8, otherwise your code would not work with the command in the first form too (text 1 thru 8),

  2. the unnecessary (and harmful) repeat loop is to blame in everything. Because the name of the folder changes on the first pass and the old folder for Finder does not exist on the second pass, when text 2 thru 8 tries to change the name of a folder that does not already exist.

So, remove repeat with i loop:


-- repeat with i in this_folder_list -- DELETED
			set first_item to item 1 of dropped_items -- name of entire path
			set theFile to (name of first_item)
			if kind of first_item is "folder" then
				set name of first_item to (text 2 thru 8 of theFile)
			end if
		-- end repeat -- DELETED

cool dude…

well, you’re first conclusion is wrong. It renames the files to just the first 8 chars. don’t worry, it wasn’t in the book.

and you’re second conclusion is correct.