Search and replace text in multiple files (experimental)

This script is an experiment in using “tops” - a command line command that will search and replace text in a file or multiple files. The version here uses tops’ most basic feature. A lot more power is available with tops - and I am looking at adding other features to this script.

(Use Scripts > Import > Man page to grab a copy of the tops man page.)

Use this with care - it’s been tested here - but not where you are - and could destroy your data :unamused:

For now, the script operates on DTPO text files (kind == “Text”, “RTF”, “HTML”) - I doubt tops could be used with PDFs (at least, that doesn’t work over here) and I wouldn’t hazard it on Office, iWork, or other proprietary file types. I’ve safeguarded the script so that it shouldn’t go there.

You’ll need the Apple Developer tools installed in order to get access to tops.

Comments welcome.


(* v0.1 Replace text using tops.scpt
This script prompts for text to search and replace, and then uses the command line "tops" command to do the replacement.
The script operates only on text files (RTF, Text, HTML types in DTPO).
The Apple Developer tools should be installed in order to get access to "tops". This is a proof of concept script.  Tops is a powerful command, and can use
regex patterns, input files that define the replacement rules, as well as other features. Tops is intended for developers, but works for any text source.
The script below is experimental - it might wipe out your data, so don't use it until you've tested it in your own environment.
*)

on run
	tell application id "com.devon-technologies.thinkpro2"
		if selection is {} then error "Please select some records"
		set oSearchText to quoted form of (display name editor "Find what?" info "<search>")
		set oReplaceText to quoted form of (display name editor "Replace with?" info "<replace>")
		repeat with oThisItem in (selection as list)
			if the kind of oThisItem is in {"RTF", "Text", "HTML"} then
				set strPath to quoted form of (path of oThisItem as string)
				set strTopsCmd to "tops replace " & oSearchText & " with " & oReplaceText & " " & strPath
				do shell script strTopsCmd
			end if
		end repeat
	end tell
end run