Duplicate files that contain specific text

Hi everyone, a question here from a scripting novice.

I have a folder with 17,000 HTML files and i want to duplicate only those files that contain a specific block of text (in this case, the text “009999”).

I found the “read” command will tell you if a file’s content contains a desired text block, like so:

if (offset of "009999" in (read "filename.html")) = 0 then
	display dialog "Not found!"
else
	display dialog "Found!"
end if

So I tried to run this on all the files in a given folder, then duplicate those files in which the text was found:

tell application "Finder"
	set theOrigin to folder "Origin" of desktop
	set theDestination to folder "Destination" of desktop
	set theFileList to (files of theOrigin)
	repeat with theFile in theFileList
		set theFileName to displayed name of theFile
		if (offset of "009999" in (read "theFile")) = 0 then
			beep
		else
			duplicate theFile to theDestination
		end if
	end repeat
end tell

Needless to say, this didn’t do the trick. Among other things, the error I get appears to indicate that you can’t perform a read on a file in the manner that I’ve attempted.

Like everyone says, any help would be appreciated!

AppleScript: 2.2.1
Browser: Safari 534.48.3
Operating System: Mac OS X (10.7)

Hi,

try this


tell application "Finder"
	set theOrigin to folder "Origin" of desktop
	set theDestination to folder "Destination" of desktop
	set theFileList to (files of theOrigin)
end tell
repeat with theFile in theFileList
	set rawText to read file (theFile as text)
	if (offset of "009999" in rawText) = 0 then
		beep
	else
		tell application "Finder" to duplicate theFile to theDestination
	end if
end repeat

Ah-ha – “read file as text.” Fantastic. Just ran your edited script and it did exactly what I was looking for.

Many thanks Stefan! Appreciate the lesson and the help.