Appending a line to a file in the cat command?
You can leverage cat
's ability to read from stdin combined with it's ability to read multiple files to achieve this.
~$ cat file.txt
Hello from file.txt
~$ echo "My final line" | cat file.txt -
Hello from file.txt
My final line
You can also prepend a line, as such:
~$ echo "My final line" | cat - file.txt
My final line
Hello from file.txt
Note that you are not limited to a single line. cat
will read from stdin until it reaches EOF. You can pass the output from curl
, for example, to prepend or append to the output of cat
.
~$ curl -s http://perdu.com | cat file.txt -
Hello from file.txt
<html><head><title>Vous Etes Perdu ?</title></head><body><h1>Perdu sur l'Internet ?</h1><h2>Pas de panique, on va vous aider</h2><strong><pre> * <----- vous êtes ici</pre></strong></body></html>
For appending a line to a file, you can just use shell append redirection operator, >>
(the file will be open(2)
-ed with O_APPEND
flag):
echo 'My final line' >>file.txt
Now, if you want just to view the content of the file with a final line appended, i would use cat
with two arguments:
- First, your file obviously, let's say
file.txt
- Second argument would be the string of your choice, and to pass the string as a filename (as
cat
only deals with files) you can leverage process substitution,<()
, which would return a file descriptor (/proc/self/fd/<fd_number>)
.
Putting these together:
cat file.txt <(echo 'My final line')
If you want the output to be paged, assuming less
is your favorite pager:
less file.txt <(echo 'My final line')
sed -e '$aMy final line' file.txt
From man sed
the option -e
-e script, --expression=script
add the script to the commands to be executed
$
matches the last line and a
appends the string.
If you wanted to permanently append the line to the file, use -i
-i[SUFFIX], --in-place[=SUFFIX]
edit files in place (makes backup if SUFFIX supplied)
Changing the command to
sed -i -e '$aMy final line' file.txt