Script to clean folder content

I have a folder that contains identical documents, but with numbers at the end. I explain. If the original is called XYZ.FileExtension, there are files in there called XYZ.FileExtension 1 and XYZ.FileExtension 2, etc. Some have one space before the number and some two.

The script works except that it always leaves one original and one copy with a number at the end. Mostly always the one with a 2.

I am lost as to how to fix this. Any tips ideas?

Also, it runs slowly on the Mac. The folder has about 500+ items and might take 10 minutes. Maybe that is just so, but it could be fun to fix that too if it’s easy, but I can happily live with it.

Thanks.

set targetFolder to choose folder with prompt "Select the folder to clean up:"

tell application "Finder"
	set fileList to (get name of every file of targetFolder)
	set baseNames to {}
	
	repeat with aFile in fileList
		set baseName to (text 1 thru ((length of aFile) - 6) of aFile) -- Get base name (excluding number and extension)
		
		if baseName is not missing value then
			if baseNames contains baseName then
				set fullPath to (targetFolder as text) & aFile
				delete (every file of targetFolder whose name is aFile)
			else
				set end of baseNames to baseName
			end if
		end if
	end repeat
end tell

Why did you put the numbers at the end of the filenames. By doing so the computer thinks “.FileExtension 1” is the file extension. I would have named them “XYZ(2).FileExtension” to “XYZ-2.FileExtension”

Also you have a “- 6” in your parsing. Is the file extension always the same length?
How Many files are there typically in your folder?

I also would have used text item delimiters to parse the filename.
I also would use “System Events” instead of “Finder”, as Finder is much slower doing file operations.

Here is a script I modified from yours…

local tid, targetFolder, fileList, aFile, baseName, nextName
set targetFolder to choose folder with prompt "Select the folder to clean up:"
set tid to text item delimiters
set text item delimiters to "."
tell application "System Events"
	set fileList to name of files of targetFolder
	set targetFolder to targetFolder as text
	my quickSort(fileList) -- sort the list alphabetically in ascending order
	set baseName to ""
	repeat with aFile in fileList
		set aFile to contents of aFile
		try -- skips files without an extention
			set nextName to (items 1 thru -2 of (text items of aFile)) as text -- file name without extension
			if nextName = baseName then
				set fullPath to targetFolder & aFile
				move file fullPath to trash
			else
				set baseName to nextName
			end if
		end try
	end repeat
end tell
set text item delimiters to tid

on quickSort(blist) -- Quick-Sort routine to sort in ascending order
	local px, lo, hi, L, H, sw -- px means 'Pivot Index'
	script q
		property alist : blist
		property stack : {{1, count blist}}
	end script
	--=Q
	--set end of Q's stack to {1, count Q's alist}
	repeat until (count q's stack) = 0
		set lo to item 1 of item 1 of q's stack
		set hi to item 2 of item 1 of q's stack
		set q's stack to rest of q's stack
		set px to item ((hi + lo) div 2) of q's alist -- start partitionHoare
		set L to lo
		set H to hi
		repeat
			repeat while item L of q's alist < px
				set L to L + 1
			end repeat
			repeat while item H of q's alist > px
				set H to H - 1
			end repeat
			if L ≥ H then exit repeat
			set sw to item L of q's alist
			set item L of q's alist to item H of q's alist
			set item H of q's alist to sw
			set L to L + 1
			set H to H - 1
		end repeat
		set px to H -- end of partitionHoare
		if px + 1 < hi then set beginning of q's stack to {px + 1, hi}
		if lo < px then set beginning of q's stack to {lo, px}
	end repeat
end quickSort

The following AppleScript will be faster than Finder or System Events. It will prompt you for the folder containing the files with bogus extensions, which it will cleanup. Files will be renamed from foo1.ext 2 to foo1.ext. The assumption is that the basename of all of these files is not the same, as that will cause the script to fail in the rename phase.

-- clean_ext.applescript
-- rename file1.ext 2 to file1.ext

use framework "Foundation"
use AppleScript version "2.8"
use scripting additions

property ca : current application

set theDir to POSIX path of (choose folder default location (path to desktop)) as text

set dirURL to ca's NSURL's fileURLWithPath:theDir
set enumOpts to (ca's NSDirectoryEnumerationSkipsPackageDescendants as integer) + (ca's NSDirectoryEnumerationSkipsHiddenFiles as integer)

-- omit any numbers or spaces in file extension
set regex to ca's NSString's stringWithString:"^.*\\.[[:alpha:]]*"
set fileArray to ca's NSMutableArray's array()

set fm to ca's NSFileManager's defaultManager()
fileArray's addObjectsFromArray:(((fm's enumeratorAtURL:dirURL includingPropertiesForKeys:{} options:enumOpts errorHandler:(missing value))'s allObjects())'s valueForKey:"path")


repeat with afile in fileArray
	set match to (afile's rangeOfString:regex options:(ca's NSRegularExpressionSearch))
	(fm's moveItemAtPath:afile toPath:(afile's substringWithRange:match) |error|:(missing value))
end repeat

-- cleanup the array of original filenames
fileArray's removeAllObjects()
display dialog "File renaming complete."
return

Tested on macOS Tahoe 26.1