Ubuntu – Appending a line to a file in the cat command

catcommand lineechopipe

I can do cat file.txt to get the contents of a file but I also want to tack on a final line of my own choosing.

I tried piping (cat file.txt ; echo "My final line") | but only the final line is getting passed through the pipe. How can I join the cat and final line?

Edit for a point of clarification: I do not wish to modify the file itself. I am aware that if this were the case I could do echo "My final line" >> file.txt or echo "My final line" | tee -a file.txt but I am only trying to do the append within the context of this particular command so I can pipe in the concatenation of file.txt and "My final line".

Best Answer

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 &ecirc;tes ici</pre></strong></body></html>