Re: search and replace
Re: search and replace
- Subject: Re: search and replace
- From: Nigel Garvey <email@hidden>
- Date: Sat, 23 Mar 2002 02:50:47 +0000
Arthur J Knapp wrote on Fri, 22 Mar 2002 14:07:28 -0500:
>
> From: Brian Mather <email@hidden>
>
> Subject: search and replace
>
> Date: Fri, 22 Mar 2002 10:40:14 -0500
>
>
> tell application "Finder"
>
> set the_file to choose file -- for development
>
> set foo to read the_file
>
> set got_it to the offset of "sometext" in foo
>
> if got_it is not 0 then
>
> beep 3 -- development again
>
> set file_mark to got_it
>
> set munger to open for access file (the_file) with write
>
> permission
>
> write "some_other_text" to munger starting at file_mark
>
> close access munger
>
>
> problem is that the write command overwrites things instead of inserting
>
> them. I'm sure some reg ex stuff would be more elegant but I don't know
>
the
>
> syntax and hadn't the time to learn it last night.
>
>
>
> Any thoughts on how I could isolate the retrieved text and replace it with
>
> the new text correctly?
>
>
If you have the memory, the simplest way to do this in AppleScript is
>
simply to read the file in, process it's contents, set eof to 0, and
>
then write the whole file out from scratch:
It certainly is. Slightly less simply, it's possible to compromise a
little and to rewrite the file just from the first edit. The method below
doesn't require the final, edited text to be assembled in memory. It may
also be faster if you have lots of large files, they only require one
edit each, and this occurs near the end of the file. ;-) Anyway, the
factors involved are quite interesting:
set searchText to "sometext"
set replaceText to "some_other_text"
set AppleScript's text item delimiters to {search_text}
set theFile to open for access (choose file) with write permission
try
set theText to read theFile as text
-- The first edit will come after the first text item -
-- which therefore needn't be overwritten in the file
set editPoint to (count theText's text item 1) + 1
-- If the first text item isn't the entire text, then
-- the text must contain the search string (the delimiter)
if editPoint does not come after (count theText) then
-- Lose everything in the file after the edit point
set eof theFile to editPoint
-- Reset the file pointer to here
write "" to theFile starting at editPoint
-- Alternately write the replacement text
-- and the next text item to the file
repeat with i from 2 to (count theText's text items)
write replace_text to theFile
write text item i of theText to theFile
end repeat
end if
on error
end try
close access theFile
set AppleScript's text item delimiters to {""}
NG
_______________________________________________
applescript-users mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/applescript-users
Do not post admin requests to the list. They will be ignored.