Use AppleScript to append text to document without new line
I want to append text to a document without new line with AppleScript. I can do it with this:
do shell script "echo -n 'text_to_append'>> mydocument"
Is there a solution that does not exploit a shell script?
If I set the text body the content of document is overwritten!
set f to POSIX file "/path/to/mydocument.txt"
write "text to append" to f starting at eof
The write
and get eof
functions are both part of AppleScript's standard additions. If the starting at
parameter is omitted, it writes the text starting at the last write position (which in this case would be the beginning of the file) and overwrites characters as it goes.
eof
denotes the end of the file.
EDIT (2020-10-26): Thanks to a comment, I should clarify that the file needs to exists prior to using the write
command. The POSIX file
specifier is also superfluous. A more complete version of the above example would look like this:
set f to "/path/to/mydocument.txt"
close access (open for access f)
write "text to append" to f as "utf8" starting at eof
The second line will create the file if it doesn't exist, and have no effect it already exists. It's now recommended to declare the data type when writing out, for which "utf8"
is a good choice if writing plain text.