24

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

daisy
  • 54,555

1 Answers1

35

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.

Guru
  • 5,905
  • These do not work for empty files - there will be nothing prepended! – Volker Siegel Aug 04 '14 at 01: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 –  Aug 14 '14 at 02: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 04 '21 at 08:57