AppleScript: How to write to a specific line of a text file?
Edited version:
set selected_file to ((path to documents folder as text) & "hom.txt") as alias
set text_data to "This is the newcomer sentence."
InsertLine(selected_file, text_data, 4)
on InsertLine(the_file, the_data, num_line)
try
set file_id to open for access the_file with write permission
set text_data to read file_id
-- CHECK EMPTY LINE
if (paragraph num_line of text_data) ≠ "" then
set the_offset to (offset of (paragraph num_line of text_data) in text_data) - 1
set remaining_data to (the_data) & (text the_offset thru -1) of text_data
set eof of file_id to the_offset
else -- LINE IS EMPTY
set num_line to num_line - 1
set the_count to (count of (characters of (paragraph num_line of text_data))) - 1
set the_offset to (offset of (paragraph num_line of text_data) in text_data) + the_count + 2
set remaining_data to the_data & linefeed & ((text (the_offset + 1) thru -1) of text_data)
set eof of file_id to the_offset - 1
end if
-- WRITE DATA TO FILE
--write the_data to file_id -- INSERT LINE
write remaining_data to file_id -- WRITE REMAINING DATA
close access file_id
on error
try
close access the_file
end try
end try
end InsertLine
I'm not sure this is the most efficient way, but this will accomplish what you're looking for. Works for me on latest version of Sierra
tell application "TextEdit" to make new paragraph at after third paragraph of text of document 1 with data "This is the newcomer sentence. \n"
UPDATED ANSWER: OPTION 2
This Would Be My Choice.
property theFile : POSIX path of (path to desktop as text) & "test.txt"
property newContent : missing value
property sedSTDOUT : "sed " -- This Option For Testing
property sedOverwriteFile : "sed -i ' ' " -- This Option Overwrites The File
addNewSentence(sedSTDOUT, "sentence C.", "This is the newcomer sentence.")
--addNewSentence(sedOverwriteFile, "sentence C.", "This is the newcomer sentence.") -- Writes To The File
to addNewSentence(whichSED, lastTextItemsOfSentenceToAddNewSentenceAfter, newSentenceContent)
set newContent to do shell script whichSED & "'s/" & lastTextItemsOfSentenceToAddNewSentenceAfter & ¬
"/" & lastTextItemsOfSentenceToAddNewSentenceAfter & "\\" & linefeed & ¬
newSentenceContent & "/' " & quoted form of theFile
return newContent
end addNewSentence