Clean up single-item tags

I had to import a large number of Evernote records. I now have a lot of tags with a single member item.

I’d like to automate these steps for all these tags:

  • Append the tag to the title of the DT document

  • Remove the tag from the DT document

  • Move the tag to DT trash

I’m trying to cobble together other scripts, but I’m sure there is a more elegant approach. Any help appreciated.

This script should perform the desired tasks. As this isn’t undoable, I’d recommend to create a copy of your database first (e.g. via File > Export > Database Archive…)


tell application id "DNtp"
	try
		set theDB to current database
		set theTags to children of tags group of theDB
		
		repeat with theTag in theTags
			set theTaggedItems to children of theTag
			if (count of theTaggedItems) is 1 then
				set theChild to item 1 of theTaggedItems
				
				-- Ensure document is not only located inside the tag
				if (count of parents of theChild) > 1 then
					set name of theChild to (name of theChild) & " - " & (name of theTag)
					delete record theTag
				end if
			end if
		end repeat
	on error error_message number error_number
		if the error_number is not -128 then display alert "DEVONthink Pro" message error_message as warning
	end try
end tell