I was trying to write a script to add a trademark header to my .cpp file. my solution is as follows.
cat trademark.txt test.cpp > new_test.cpp && mv new_test.cpp test.cpp
However, wanted to know if there is a better way of doing this.
3 Answers
You can use awk like this:
awk 'NR==FNR && !h {print;h=1;} NR!=FNR{print}' headerFile mainFile > tmpFile
mv tmpFile mainFile
Using vim/vi:
vim +'0r headerFile|wq' mainFile 2>/dev/null
Using GNU sed:
sed -i.bak -e '2{x;G};1{h;rheaderFile' -e 'd}' mainFile
Using non-GNU sed:
HDR=$(head -1 headerFile) && sed -i.bak "1s/^/$HDR/" mainFile
You've already accepted an answer, but I'll suggest one more way:
sed -i -e '1r trademark.txt' -e '1{x;d;};2{H;g;}' test.cpp
If you're using vim, check out ultisnips. It can do this, and much more.
E.g., I've defined the following snippet to add a public domain header to a file:
snippet pd "Public domain dedication" b
#
# Author: ${1:Roland Smith} ${2:<>}
# \$Date: `!v strftime("%F %T %z")` \$
#
# To the extent possible under law, $1 has waived all copyright and
# related or neighboring rights to `!v expand('%:t')`. This work is published
# from the Netherlands. See
endsnippet
To use this snippet, I insert pd at the beginning of a line in vim and hit <tab>. This expands the snippet, filling in the current date in the $Date$ tag, and fills in the filename (using expand). It then highlights the name of the author which is the first variable, allowing me to change it if necessary. This automatically changes all further instances of that variable. Using <ctrl>j takes me to the following variable, the author's email address, which can also be changed if desired.
You can use vimscript commands (between quotes and prepended by !v). If your vim is compiled with Python support you can also use Python code with !p.