TextEdit: Find and replace

Finds and replaces all instances. Put the text to find and replace between the quotes indicated. (Requires UI scripting enabled.)

--Find and Replace in TextEdit
tell application "TextEdit" to activate 
tell application "System Events"
tell process "TextEdit"
tell window "Find"
keystroke "PutTheTextYouWantToFindHere"
keystroke tab
keystroke "PutTheTextYouWantToReplaceItWithHere"
click button "Replace All"
end tell
end tell
end tell

:frowning: I tried your script and it added both the “find” and the “replace” text to the current text.

Yeah, this did not work for me either. and I have UI scripting enabled

Correct script:


tell application "TextEdit" to activate

tell application "System Events" to tell application process "TextEdit"
	tell menu 1 of menu item "Find" of menu 1 of menu bar item "Edit" of menu bar 1
		click menu item "Find…"
		keystroke "oldText"
		click menu item "Find And Replace…"
		keystroke "newText"
	end tell
	tell scroll area 1 of window 1
		click UI element "All" of group 2
		click UI element "Done"
	end tell
end tell
delay 10 -- only to make the result visible to user

To replace some words in the text with other word (replace all), no need GUI scripting:


set anOldText to "oldText"
set aNewText to "newText"

tell application "TextEdit"
	activate
	tell document 1 to set words whose it is anOldText to aNewText
end tell

delay 10 -- only to make the result visible to user

And, the following script exports RTF TextEdit file to new TXT TextEdit file with replaced instances of anyone type. Is assumed that you have opened already one source RTF file in TextEdit. Without GUI scripting too:


set anOldText to "oneOldText bb" -- may include space,return and other special simbols
set aNewText to "oneNewText" -- may include space,return and other special simbols

set aFile to "/Users/123/Desktop/Untitled_Edited.txt"
try
	close access aFile
	set aFileID to open for access aFile with write permission
on error
	set aFileID to open for access aFile with write permission
end try

tell application "TextEdit"
	activate
	tell document 1
		set entireText to its text
		
		set TID to text item delimiters of AppleScript
		set text item delimiters of AppleScript to anOldText
		set aText to text items of entireText
		
		set text item delimiters of AppleScript to aNewText
		set aText to aText as text
		set text item delimiters of AppleScript to TID
		
		write aText to aFileID
		close access aFileID
	end tell
end tell

tell application "TextEdit" to open aFile