MacOS – AppleScript: How to write to text file in specific location (signaled by specific character)

applescriptmacostext;

I have a .txt file saved on my computer. I want my Automator application to add a bit of text to the .txt file (the text will be entered by the user). I already know how to append text or prepend text in AppleScript. However, I want the text to be inserted into a specific location.

For example, this is the contents of my .txt file entitled My Fruit Log.txt. This is what the .txt file looks like before the text is written to the file:

You can see where exactly I want the text to be saved in the file in this image:

Is what I want to do clear? I want the text to be written on the line directly above the first blank line found in the file. Note: It is not necessarily the second line from the top where I want the text to be written. Depending on what text has already been written to the file, the text might be saved on a lower line. For example:

The location where I want the text to be written must be at least the second line from the top, but it may also be as further down as the seventh line from the top. So, the most reliable way to articulate where I want to write the text is "on the line before the first instance of a blank line in the document."

Can this be accomplished in AppleScript?

Best Answer

Here's a shell script:

sed -i '' -e ':a' -e 'N' -e '$!ba' -e 's/\n\n/\
Write the new line you wish inserted in your file here\
\
/' ~/Desktop/file.txt

You can wrap this in a ‘do shell script’ if you really want AppleScript, but for an Automator script, you can use a Run Shell Script action and just use the shell script.


Here's an AppleScript wrapper for the script, where the TextToWrite variable and the Target_Filepath variable have been defined elsewhere per your comments:

set addline to "sed -i '' -e ':a' -e 'N' -e '$!ba' -e 's/\\n\\n/\\
" & TextToWrite & "\\
\\
/' \"" & Target_Filepath & "\""
do shell script addline