Using Automator to save text to a SPECIFIED text file (not a new file)
I know that there's a way to use Automator to save text to a new text file.
But I want an Automator application that saves the text from clipboard to a GIVEN text file (by editing it, i.e. adding in the next line). Applescript would be okay too. Is there a way to do this?
You could use an Automator workflow/application using a Run Shell Script action with:
/usr/bin/pbpaste >> '/path/to/filename.txt'
echo >> '/path/to/filename.txt'
Notes:
Check out the manual page for: pbpaste
You can read the manual page for command
in Terminal by typing command
and then right-click on it and select: Open man Page
The echo >> '/path/to/filename'
line adds a single line feed to the end of the file after the pasted text. You can add addition lines for more line feeds if you so choose.
In place of the echo
command you can also use, e.g.:
printf '\n' >> '/path/to/filename.txt'
Adding additional \n
for more line feeds, e.g. '\n\n'
.
If you update the file while it's opened, it is not doing to show the updated contents, you need to close/reopen the file to see additional updates to it.
If you want to do it with AppleScript, then in place of the Run Shell Script action, use a Run AppleScript action with the following example AppleScript code wish uses a slightly modified handler from Reading and Writing Files:
set myFilename to (path to documents folder) & "Clipboard Text.txt"
set cbText to ((the clipboard) as text) & linefeed & linefeed
writeTextToFile(cbText, myFilename, false)
on writeTextToFile(theText, theFile, overwriteExistingContent)
try
-- Convert the file to a string
set theFile to theFile as string
-- Open the file for writing
if theFile contains "/" then
set theOpenedFile to open for access theFile with write permission
else
set theOpenedFile to open for access file theFile with write permission
end if
-- Clear the file if content should be overwritten
if overwriteExistingContent is true then set eof of theOpenedFile to 0
-- Write the new content to the file
write theText to theOpenedFile starting at eof
-- Close the file
close access theOpenedFile
-- Return a boolean indicating that writing was successful
return true
-- Handle a write error
on error
-- Close the file
try
close access file theFile
end try
-- Return a boolean indicating that writing failed
return false
end try
end writeTextToFile
Notes:
The handler from the linked Apple support document was modified to handle both POSIX and HFS+ file paths.