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
4 thoughts on “Insert/Add String to Beginning of a File”
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.
Perfect little one liner! Thank you!
Excellent. Thank you!