Insert/Add String to Beginning of a File

bash arguments, pass parameter, pass argument to script

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

  1. 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
  2. Run the command:
    sed -i '1i Top of the file!' <filename>
  3. 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

See also  Linux Tips: How to Concatenate Strings in Bash

5 thoughts on “Insert/Add String to Beginning of a File”

  1. 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

Leave a Comment