Add header to tab delimited file

I would like to add a header to the tab delimited file, but I'm not sure how to do this on a single line in linux.

Say my file is:

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

and now I would like to add a headline that reads:

 name\tage\tuniversity\tcity 

How do I do this on a single line in linux? I'm fine with awk, sed, cat, etc., Not familiar at all with perl, though.

+7
source share
6 answers

There is no prepend statement such as append >> , but you can write the header to a temp file, then copy the contents of your file to the temp file and move it back

 echo -e "name\tage\tuniversity\tcity" | cat - yourfile > /tmp/out && mv /tmp/out yourfile 
+12
source
 $ { printf 'name\tage\tuniversity\tcity\n'; cat orig-file; } > new-file 

or

 $ printf '1\ni\nname\tage\tuniversity\tcity\n.\nw\n' | ed -s orig-file 
+8
source

Personally, I would go with nano -w file.txt ;-) (i.e. just use a text editor, it doesn't have to be nano)

But if you want to do this in a non-interactive environment for any reason, you can use cat for all kinds of concatenations:

 echo $'name\tage\tuniversity\tcity' | cat - file.txt > file2.txt 

will add a header and put the output in file2.txt . If you want to overwrite the original file, you can do this with

 echo $'name\tage\tuniversity\tcity' | cat - file.txt > file2.txt; mv file{2,}.txt 

Or you can use sed as follows:

 sed -i $'1 i\\\nname\tage\tuniversity\tcity' file.txt 

Note that I'm using $'...' quoting to allow me to use \t to represent a tab and \n to represent a new line (among other substitutions, see the bash man page for more). In this type of quoted string, \\ is a literal backslash. So the program passed to sed is actually

 1 i\ name age university city 
+6
source
 perl -i -lne 'if($.==1){print "newline\n$_"}else{print}' your_file 
+3
source

First create a file with the contents of the header:

 $ cat >header name^Iage^Iuniversity^Icity (return) ^D 

(where ^I is the tab key)

Then add it to the data

 $ cat header myfile >newfile $ mv newfile myfile 
+1
source
 cat <(head -1 theFileWithHeader) theFileWithoutHeader > newfile; mv newfile theFileWithoutHeader; 
0
source

All Articles