How to Write/Append Multiple Lines to a File from terminal?
Sometimes you might be needed to write or append some text to a file from the terminal. You can use different strategies to write multiple lines to a record file through the command line. This article explains some of them.
Append to a File using the Redirection Operator (>>)
Redirection Operator (>>
) allows you to catch the output from a command and send it as input to another command or file. You can use echo
and printf
commands with Redirection Operator (>>
) to print text to the standard output and write it to the file.
To append text to a file, specify the name of the file after the redirection operator:
echo "this is a new line" >> file.txt
If you want to interpret the backslash-escaped characters such as newline \n
, for that you need to use -e
option with the echo
command:
echo -e "this is a new line \nthis is another new line" >> file.txt
For more complex output, use the printf
command, which allows you to specify the formatting of the output:
printf "Hello, I'm %s.\n" $USER >> file.txt
Another approach to add text to a file is to utilize the Heredoc
. It is a sort of redirection that permits you to pass multiple lines of input to a command.
For instance, you can pass the content to the cat
command and append it to a file:
echo "line 1 content
line 2 content
line 3 content" >> myfile.txt
You can append the output of any command to a file. Here is an example with the date
command:
date +"Year: %Y, Month: %m, Day: %d" >> file.txt
When you are appending to a file using a redirection operator (>>
), be mindful so as not to use the >
operator, because it will overwrite the existing content of the file.
Append to a File using the "tee" Command
tee
is a command-line utility in Linux that reads from the standard input and writes to both standard output and multiple files simultaneously.
By default, the tee
command overwrites the specified file. To append the output to the file, use tee
with the -a
(- -append
) option:
echo "this is a new line" | tee -a file.txt
If you do not want tee
to write to the standard output, redirect it to /dev/null
:
echo "this is a new line" | tee -a file.txt >/dev/null
The benefit of utilizing the tee
command over the >>
operator is that tee
allows you to append text to multiple documents at the same time, and to write to files owned by different users in conjunction with sudo
.
To append text to a file that you don't have write permissions, prepend sudo
before tee
:
echo "this is a new line" | sudo tee -a file.txt
tee
gets the output of the echo command, elevates the sudo
permissions, and writes to the file.
To append text to multiple files, specify the files as arguments to the tee
command:
echo "this is a new line" | tee -a file1.txt file2.txt file3.txt
Please login or create new account to add your comment.