23

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

EDIT2

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

EDIT

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

3
  • 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
  • 3
    In case writing to tmpfile fails for some reason, use && mv ... instead of ; mv ... -- that will keep $file from being overwritten with "bad" content. Nov 28 '12 at 15:45
32

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
hi
hello
$ cat file2
welcome to
Unix SO.

The sed command:

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

The output after the sed command :

$ cat file2
hi
hello
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.

4
  • These do not work for empty files - there will be nothing prepended! 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
    – user6860
    Aug 14 '14 at 2:28
  • 5
    this is one of those cases where I'd argue there should be a widespread prepend command.
    – Andy
    Jun 14 '17 at 21:28
  • macOS counterpart would be sed -i '' '1i\ #GPL License' file (after i\ there should be line break)
    – kambala
    May 4 '21 at 8:57

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