Possible Duplicate:
How can I prepend a tag to the beginning of several files?

Other than create a temporarily file with a line at the heading, and move it back when finished, is there a standard way to prepend some lines to a file?

i.e sometimes you do (echo #GPL license; cat $file) > tmpfile; mv tmpfile $file


In the first place, I was just trying to see if there's a standard command that ships with common distros, I guess not


And notice that the source to prepend might not just be a fixed string, it could be a file as well, i.e cat $header $file > tmpfile; mv tmpfile $file

  • what do you mean by "line at head"? – Guru Nov 28 '12 at 11:57
  • @Guru i.e (echo #GPL license; cat $file) > tmpfile; mv tmpfile $file – daisy Nov 28 '12 at 12:04
  • 2
    In case writing to tmpfile fails for some reason, use && mv ... instead of ; mv ... -- that will keep $file from being overwritten with "bad" content. – glenn jackman Nov 28 '12 at 15:45

If sed(GNU) is ok for you :

$ sed -i '1i #GPL License' file

In case of the source being a file:

The source files:

$ cat file1
$ cat file2
welcome to
Unix SO.

The sed command:

$ sed -i  '1{
r file1
};2{H;g;}' file2

The output after the sed command :

$ cat file2
welcome to
Unix SO.

The 'r' command of sed cannot read a file before the 1st line, and hence this solution. The 1st line is kept in hold memory, the contents of file1 are sent to terminal, then when the second line comes, it is printed together with 1st line.

|improve this answer|||||
  • These do not work for empty files - there will be nothing prepended! – Volker Siegel Aug 4 '14 at 1:31
  • 7
    The version of sed on OS X objects to the syntax sed -i '1i #GPL License' file with the error message invalid command code f – sampablokuper Aug 14 '14 at 2:28
  • 3
    this is one of those cases where I'd argue there should be a widespread prepend command. – Andy Jun 14 '17 at 21:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.