Try using:
set the_array to {}
tell application "Finder"
try
set theLocation to the selection as alias
on error
set theLocation to (folder of the front window as alias)
end try
repeat with this_file in (get files of theLocation)
set the_name to name of this_file
set the_prefix to items 1 thru ((offset of "_" in the_name) - 1) of the_name as string
if the_array does not contain the_prefix then set the_array to the_array & the_prefix
end repeat
repeat with e in the_array
if not (exists folder e of theLocation) then make new folder at theLocation with properties {name:e}
end repeat
set this_list to every file of theLocation
set AppleScript's text item delimiters to {"_"}
repeat with i in this_list
repeat with ee in the_array
try
if (name of i) begins with ee then
move i to folder ee of theLocation
set name of (the result) to text item 2 of (get name of (the result)) as string
end if
end try
end repeat
end repeat
end tell
(98842)