Reputation: 10558
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.
Upvotes: 9
Views: 13064
Reputation: 38619
Sorry to use up a whole answer - just for the sake of formatting :) Basically, the same answer from @tangens, but without the temporary file:
echo "$(cat header.txt sample.txt)" > sample.txt
Note the quotes ("
) to preserve the line endings, and the fact that the cat
concatenation runs in a subprocess - so there shouldn't be the possibility of overwriting a file (the sample.txt
) which is open for reading..
Cheers!
Upvotes: 11
Reputation: 359905
If you have GNU sed
:
sed -i -e '2{x;G};1{h;rheader.txt' -e 'd}' sample.txt
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.
Upvotes: 10
Reputation: 6016
Use ed text editor:
echo -e '0r header.txt\nw' | ed sample.txt
or use vi/ex command:
vi - +'0r header.txt|wq' sample.txt
But I don't see any way to run a command in sed.
Upvotes: 8
Reputation: 2585
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
for f in *.c
do
cp $f /tmp
cat copyright.txt /tmp/$f >$f
done
Upvotes: 0
Reputation: 454950
If you really want to do it using sed
:
INFO=$(cat header.txt) # read the contents of file headers.txt into var INFO
sed -i "1i$INFO" sample.txt # insert $INFO, use -i to change the file inplace
I would however use the cat
based method.
Upvotes: 1