I believe this is my first question at MacScripter, I hope someone can shed some light on this topic.
My goal is to add text to a text file at a certain point. For example if I had a text file with the contents:
"
– Name –
Erik
– Problem Description –
– OS Type –
Mac OS X
"
I would like to know how I could use AppleScript to insert text right under the “-- Problem Description --” part of the text file.
Assume that I’ve already got a file reference and the file is open for write permission. This question is more about how to ‘place the text cursor at a certain point in the text document and add text to a file’.
There’s no magic insert command – you have to read the rest of the file and store it, write the new information, then write the stored information after it.
You can use text items delimiters, to insert a text at a given place, the text you know to come exactly before it, and that occrs only once to be the text items delimiters, and yes, the text has to exist, or it crashes.
I provide a sketch; you’ll need read and write handlers, which you will find an abundance of here.
set tids to AppleScript's text item delimiters # preserves original value
set theText to read_text # text read into the text
set AppleScript's text item delimiters to theHeader # whatever that should be before textToInsert
set newTExt to text items of theText # makes the text into a list.
set item 2 of newTExt to return & textToInsert & return & item 2 of newTExt # adds new text
set newTExt to newTExt as text # makes our list back into a text
set AppleScript's text item delimiters to tids # resets text item delimiters, important!
write newTExt # writes the changed data back to a file
It’s easiest to read the entire file, edit the text in AppleScript using a scheme like that sketched out by McUsr, then write the result back to the file ‘starting at 1’. (Better still, ‘set eof’ the file to 0 first.) Don’t forget when using the ‘read’ and ‘write’ commands that you have to know what class of text is in the file (‘string’, ‘Unicode text’, or «class utf8») and to read and write ‘as’ that particular class.