Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script to add header to a file

Tags:

shell

vim

unix

sed

awk

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.

like image 527
Jack Avatar asked Jul 17 '13 11:07

Jack


People also ask

How do I add a header to a file?

Go to Insert > Header & Footer. Add or header or footer text.


1 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
like image 55
anubhava Avatar answered Sep 20 '22 07:09

anubhava