In a previous article, I showed you how to append a string to the end of file. Now I will show you how to insert a string to the beginning of a file in Linux. The solution is not as obvious as the former, but I will show you a quick and easy way using the standard Linux/Unix application sed.
Inserting a String to Beginning of File
- Suppose you had a text file with the contents and you wanted to insert a string to the beginning:
- Run the command:
sed -i '1i Top of the file!' <filename>
- Now the file will look like this:
Top of the file!
A brief explanation of the sed command parameters that we used:
-i : This will update the contents of the file and automatically save it
1i : This means, insert to the 1st line of the file