I am trying to insert some copy-right information into the beginning of some source files. I know that using sed in the following way:
sed "1iSome copyrighted information." sample.txt
would insert the text "Some copyrighted information" to the beginning of sample.txt.
I need to insert text from a file to the beginning of sample.txt. Is there any way in sed that I could use a cat
command for the above purpose, say something like the following?:
sed "1i{cat header.txt}" sample.txt
I have googled for the above and have not found exactly what I have been looking for. Any help on this is most welcome.
Thanks.
If you have GNU
sed
:sample.txt must be contain at least two lines.
This method works even if the header file contains characters that are special to
sed
.Explanation:
-i
- edit the file in place-e
- break the script up into sections - this is necessary in this case to delimit the end of the header filename (it could also be delimited by a newline)1{h;
- on the first line of the file (sample.txt) save it to hold spacerheader.txt
- read in the header file (header.txt)d}
- delete the original first line of the file from pattern space and end processing of line 1 - deleting it here prevents an extra blank line from being inserted at the beginning of the file2{x;
- when line 2 of the file (sample.txt) is read, swap it into hold space and swap hold space (containing the original line 1) into pattern spaceG}
- append hold space onto the end of pattern space (which now contains original lines 1 and 2) and complete processing of line 2Edit: I removed a superfluous command from the version I originally posted.
If you really want to do it using
sed
:I would however use the
cat
based method.Why not do this the other way round, e.g. append your source files to your copyright file?
The 'cat' command is actually short for 'concatenate', you can simply say
Sorry to use up a whole answer - just for the sake of formatting :) Basically, the same answer from @tangens, but without the temporary file:
Note the quotes (
"
) to preserve the line endings, and the fact that thecat
concatenation runs in a subprocess - so there shouldn't be the possibility of overwriting a file (thesample.txt
) which is open for reading..Cheers!
Use ed text editor:
or use vi/ex command:
But I don't see any way to run a command in sed.