fReplace

AppleScript vanilla search/replace text in a file (data fork only)

OS version:

(*
fReplace
Make search/replace operations in data fork of a file(s) (eg, plain text file)
If you are working with large files (eg, plus than 5 MB) or you expect find more than 5000 ocurrences, use instead "fReplaceSafe".

Parameters:
s: search term
r: replace term
f: file path, alias, posix path or list of such (file(s) to make search/replacements in, only data fork)

Example:
fReplace("vaca", "perro", alias "path:to:file.txt")
fReplace("vaca", "perro", {alias "path:to:file1.txt", "path:to:file2.txt"})
*)

to fReplace(s, r, f)
	local s, r, f, q, t, fRef, msg, n
	script nesteed
		to searchReplace(s, r, t)
			set oldTids to AppleScript's text item delimiters
			set AppleScript's text item delimiters to s
			set t to t's text items
			set AppleScript's text item delimiters to r
			set t to t as text
			set AppleScript's text item delimiters to oldTids
			t
		end searchReplace
	end script
	
	copy f as list to q
	repeat with f in q
		set f to f as Unicode text
		if f does not contain ":" then set f to POSIX file f as Unicode text
		
		if f does not end with ":" then --> process it, is a file
			set f to alias f --> make sure the file exists or throw raw error
			
			try --> if anything is wrong, close output file
				set fRef to (open for access f with write permission)
				set t to nesteed's searchReplace(s, r, read fRef)
				set eof of fRef to 0
				write t to fRef
				close access fRef
			on error msg number n
				try
					close access fRef
				end try
				error msg number n
			end try
		end if
	end repeat
end fReplace

property |version| : 1.0
property |from| : "jfileLib"
property author : "Pescados Software ยท PescadosWeb.com"
property |date| : date "martes, 27 julio 2004 00:00:00"
property license : "freeware, open-source"