• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Insert Text Here
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Insert Text Here


  • Subject: Re: Insert Text Here
  • From: Jon Pugh <email@hidden>
  • Date: Sat, 21 Jan 2012 10:03:28 -0800

On Jan 21, 2012, at 9:04 AM, Marconi wrote:
> I need to open a text file for writing but, instead of appending text, I need to insert text at a given point.
>
> Suppose I have a text file that is like this:
>
> File starts here
> some more stuff
> insert text here.
> some more stuff too
> end of the stuff
>
>
> And suppose I wanted to insert some text ("this has been inserted") after the designator "insert text here" such that the result is:
>
>
> File starts here
> some more stuff
> insert text here.
> this has been inserted
> some more stuff too
> end of the stuff
>
> Is there a way, when writing a text file, to insert text rather than appending or overwriting?

You have to read in the whole file, modify it in memory and then write out the whole file.

Time to flog my SmartString class again. ;)

property ss : load script file ((path to application support from user domain as string) & "Script Debugger:Script Libraries:SmartString.scpt")
set file_path to (path to desktop as string) & "file.txt"
set new_path to (path to desktop as string) & "newfile.txt"
set file_text to read file file_path
set insert_location to "insert text here."
set inserted_string to "this has been inserted"
tell ss's SmartString
	setString(file_text)
	set new_text to beforeString(insert_location) & insert_location & return & inserted_string & afterString(insert_location)
end tell
set file_ref to open for access file new_path with write permission
write new_text to file_ref
close access file_ref

SmartString is available here: http://www.seanet.com/~jonpugh/software/SmartString.applescript

It’s also easier to use from Script Debugger, as you just choose it from a  popup and it’s included.  Very nice.

Jon


 _______________________________________________
Do not post admin requests to the list. They will be ignored.
AppleScript-Users mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
Archives: http://lists.apple.com/archives/applescript-users

This email sent to email@hidden


  • Follow-Ups:
    • Re: Insert Text Here
      • From: David Ferrington <email@hidden>
References: 
 >Insert Text Here (From: Marconi <email@hidden>)

  • Prev by Date: Re: Insert Text Here
  • Next by Date: Re: Open Bugs
  • Previous by thread: Re: Insert Text Here
  • Next by thread: Re: Insert Text Here
  • Index(es):
    • Date
    • Thread