Add a header to a tab delimited file

Dnaiel picture Dnaiel · Oct 15, 2012 · Viewed 41.7k times · Source

I'd like to add a header to a tab-delimited file but I am not sure how to do it in one line in linux.

Let us say my file is:

roger\t18\tcolumbia\tnew york\n
albert\t21\tdartmouth\tnew london\n
etc...

and now I'd like to add a header that says:

name\tage\tuniversity\tcity

How would I do that in one line in linux? I am ok with awk, sed, cat, etc. not familiar at all with perl though.

Answer

newfurniturey picture newfurniturey · Oct 15, 2012

There isn't a "prepend" operator like the "append" operator >>, but you can write the header to a temp-file, copy your file's contents into the temp-file after that, and move it back:

echo -e "name\tage\tuniversity\tcity" | cat - yourfile > /tmp/out && mv /tmp/out yourfile