How To Append Text To End of a File in Linux

This post will guide you how to append or add text or lines to end of a given file using the command line in the Linux Operaing systems. How do I redirect a standard output of text into a file and append it at the shell prompt in Linux.

append text to end of file linux1

Appending Text Using Cat Command


You can use the double redirection characters to append text to end of a file. And you can use cat command in combination with redirection character to print on the standard output and appending output or text to end of a given file. Assuming that you have a file called mytest.txt, and you with to append another lines of text to end of this file, just type the following command:

$ cat >>mytest.txt
[type text here]
Ctrl + d

Outputs:

[root@localhost /]# cat mytest.txt
this is a test line
[root@localhost /]# cat >>mytest.txt
this is the second line
this is the thrid line
[root@localhost /]# cat mytest.txt
this is a test line
this is the second line
this is the thrid line

Note: you can type as many lines as you want in the [type text here] area. when you are done, you need to press “ctrl+d” keys to send the end of file character.

Appending Text Using Echo Command


You can also use another command called echo in combination with redirection character to redirect the output of an “echo” command to end of a file. type:

$ echo "this is the fifth line" >> mytest.txt

Outputs:

[root@localhost /]# echo "this is the fifth line" >> mytest.txt
[root@localhost /]# cat mytest.txt
this is a test line
this is the second line
this is the thrid line
this is the fifth line

Appending Standard Output to End of a File


If you want to redirect the standard output of a command to end of a file, and you can use redirection character. For example, you want to pring the standard output of “df -h” command and append all output to end of a file called mytest.txt. type:

$ df -h >> mytest.txt

outputs:

[root@localhost /]# df -h >>mytest.txt
[root@localhost /]# cat mytest.txt
this is a test line
this is the second line
this is the thrid line
this is the fifth line
Filesystem Size Used Avail Use% Mounted on
devtmpfs 748M 0 748M 0% /dev
tmpfs 765M 0 765M 0% /dev/shm
tmpfs 765M 1.4M 763M 1% /run
tmpfs 765M 0 765M 0% /sys/fs/cgroup
/dev/mapper/fedora-root 40G 8.3G 29G 23% /
tmpfs 765M 76K 765M 1% /tmp
/dev/sda1 976M 133M 777M 15% /boot
tmpfs 153M 5.8M 148M 4% /run/user/1005
tmpfs 153M 0 153M 0% /run/user/1006

Conclusion


You should know that how to add or append text or lines to end of a given file using cat/echo commands in CentOS or RHEL or Ubuntu Linux system.

You might also like:

Sidebar



back to top