What is the easiest way to append text to a file in Linux?
I had a look at this question, but the accepted answer uses an additional program (sed
) I'm sure there should be an easier way with echo
or similar.
What is the easiest way to append text to a file in Linux?
I had a look at this question, but the accepted answer uses an additional program (sed
) I'm sure there should be an easier way with echo
or similar.
cat >> filename
This is text, perhaps pasted in from some other source.
Or else entered at the keyboard, doesn't matter.
^D
Essentially, you can dump any text you want into the file. CTRL-D sends an end-of-file signal, which terminates input and returns you to the shell.
How about:
echo "hello" >> <filename>
Using the >>
operator will append data at the end of the file, while using the >
will overwrite the contents of the file if already existing.
You could also use printf
in the same way:
printf "hello" >> <filename>
Note that it can be dangerous to use the above. For instance if you already have a file and you need to append data to the end of the file and you forget to add the last >
all data in the file will be destroyed. You can change this behavior by setting the noclobber
variable in your .bashrc
:
set -o noclobber
Now when you try to do echo "hello" > file.txt
you will get a warning saying cannot overwrite existing file
.
To force writing to the file you must now use the special syntax:
echo "hello" >| <filename>
You should also know that by default echo
adds a trailing new-line character which can be suppressed by using the -n
flag:
echo -n "hello" >> <filename>
References
echo(1) - Linux man page
noclobber variable
I/O Redirection
Other possible way is:
echo "text" | tee -a filename >/dev/null
The -a
will append at the end of the file.
If needing sudo
, use:
echo "text" | sudo tee -a filename >/dev/null
Follow up to accepted answer.
You need something other than CTRL-D to designate the end if using this in a script. Try this instead:
cat << EOF >> filename
This is text entered via the keyboard or via a script.
EOF
This will append text to the stated file (not including "EOF").
It utilizes a here document (or heredoc).
However if you need sudo to append to the stated file, you will run into trouble utilizing a heredoc due to I/O redirection if you're typing directly on the command line.
This variation will work when you are typing directly on the command line:
sudo sh -c 'cat << EOF >> filename
This is text entered via the keyboard.
EOF'
Or you can use tee
instead to avoid the command line sudo issue seen when using the heredoc with cat:
tee -a filename << EOF
This is text entered via the keyboard or via a script.
EOF