Linux Commands – Appending Text to file
In this tutorial, you can learn how to append text to a file using four different ways. They are
- Using cat command
- Using echo command
- Using printf command
- Using tee command
1. Using cat command
- Cat is a popular linux command which is used to create a next text file, display the contents of a file, merge the files, append the text to a file, etc,.
- Here text is appended to a file using the IO-redirection operator >> with cat command.
Syntax
cat >> oldfile [Append text to file]
cat f1.txt >> f2.txt [Append file content to another file]
Example
2. Using echo command
- In linux, echo command is used for displaying messages, creating files and appending the text to a file.
- Here text is appended to a file using the IO-redirection operator >> with echo command.
Syntax
echo “message” >> old file
Example
3. Using printf command
- Like echo command, printf command is used for displaying messages, creating files and appending the text to a file.
- Here text is appended to a file using the IO-redirection operator >> with printf command.
Syntax
printf “message\n” >> old file
Example
4. Using tee command
- Tee is also a popular linux command which is used for reading standard input and writing data into both standard output and one or more number of files.
- This command has a special option like -a to append the text to a file.
- Here text is appended to a file using pipe symbol | with tee command.
- Pipe is actually connecting two or more processes or commands.
- Through pipe symbol (|) , the output of one command can be given as an input of another command.
- Unlike cat, echo, printf, this tee command is used for appending text to multiple files.
Syntax
echo “message” | tee -a file1 file2 … file-n
Example – Appending text to a single file
echo “hello world” | tee -a test.txt
- Here the text “hello world” is appended to the old file test.txt with help of pipe and tee command with option -a.
- -a stands for appending and will append the text at the end of the file.
Example – Appending text to a multiple files
echo “good morning” | tee -a d1.txt d2.txt
Appending Command to file
- It is also possible to append command output to a file using double output redirection operator >>
Syntax
command >> filename
Example
ls >> res.txt
- In the above command, the output of ls command will be stored to a text file res.txt using >> operator.