How do I prepend text to a file?

Q:  I know I can redirect standard output to a text file, and the output will be written to the end of the file (append), but how do I add a line of text to the BEGINNING of a text file?

A: Easy, if you use sed. Here's an example of a commandline where I use sed to add "some text to prepend" to the begining of a file called "testfile1.txt":


sed -i '1s/^/some text to prepend\n/' testfile1.txt


Now if you look at the contents of the file, the original line 1 is now line 2, and the new line 1 reads "some text to prepend". The n at the end of the line adds a "newline" control character to the end of the line of text.