This post and this website contains affiliate links. See my disclosure about affiliate links here.
how to append or add text to a file in linux
Posted on bybarkeep
Append is defined as “to add something new to something that is existing, as an attachment or supplement“. Sometimes you will need to append text to an already existing text file. This text could come from any source, such as a line of text from the command line, the output of a command or from another text file.
The easiest way to append text is to use the operator ‘>>‘ from the Linux command line. There are two different operators that redirects output to files: ‘>‘ and ‘>>‘, that you need to be aware of.
‘>‘ is used to remove the previous contents before appending the text, while ‘>>‘ appends text while preserving the existing contents. And also, it always appends the text to the end of the file. So, if you want to append text to the end of the text then you should use the “>>” operator in your commands. We will see some examples of how this is done.
Append Single Line of Text
If you just want to quickly append a small single line of text, then you can use the echo command from the command line.
bash$ echo "This is just a single line of text" >> ./path/filename.txt
Append Text from Command Prompt (Multiple Lines)
If you want to append a long line of text or multiple lines then using the echo command can be cumbersome. In this case, you can direct the stand input (stdin) to the file instead.
When you use the following command, the cat command reads from the stdin and the “>>” operator redirects the standard input to the file, which means you will not return back to the prompt unless you exit (close the stream) using Ctrl-D