Script to remove all spaces in file names in all nested folders

I need a script that will look through all of the files in a folder and all nested folders and simply remove all spaces in those file names. I have been using the script below and it works fine with one folder, but I can’t figure out how to edit it so that it will also go through all of the nested folder as well. Suggestions?

set defDel to AppleScript’s text item delimiters
tell application “Finder”
set theFolder to folder (choose folder)
repeat 20 times
repeat with thisItem in theFolder
set thename to name of thisItem
if thename contains " " then
set AppleScript’s text item delimiters to " "
set newname to text items of thename
set AppleScript’s text item delimiters to “”
set name of thisItem to (newname as string)
set AppleScript’s text item delimiters to defDel
end if
end repeat
end repeat
end tell

I have not fully tested this, but it should work:


tell application "Finder"
	set theFolder to folder (choose folder)
	set allSpacedOutFiles to (every file in entire contents of theFolder whose name contains " ")
	repeat with thisItem in allSpacedOutFiles
		set thename to name of thisItem
		set name of thisItem to my RemoveSpaces(thename)
	end repeat
end tell


to RemoveSpaces(txt)
	set defDel to AppleScript's text item delimiters
	set AppleScript's text item delimiters to " "
	set newname to text items of txt
	set AppleScript's text item delimiters to ""
	set correctedName to (newname as string)
	set AppleScript's text item delimiters to defDel
	return correctedName
end RemoveSpaces

By using the term entire contents, you can gather all of the files within all the subfolders of a selected folder that meet certain criteria. In this case, if the name has a space.

Good luck,