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:
1st line
2nd line
3rd line
- Run the command:
sed -i '1i Top of the file!' <filename>
- Now the file will look like this:
Top of the file!
1st line
2nd line
3rd line
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
Many thanks,
I was writing a script to automate the syslog installation with log analyzer and wanted to automate the editing of /etc/rsyslog.conf. So, I sued “sed -i ’22i $InputTCPServerRun 514′ /etc/rsyslog.conf”.
This sed work around is also useful for me to make editing easier.
-Girish
Perfect little one liner! Thank you!
Excellent. Thank you!
How do I do this with sed -e?
sed -i is not a recognized flag on AIX