Add a header to a tab delimited file

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

But if you wanted to do this in a non-interactive environment for some reason, you can use cat for all sorts of concatenations:

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

will prepend the header and put the output in file2.txt. If you want to overwrite the original file you can do it with

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

Or you could 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 tab and \n to represent newline (among other substitutions; see the bash man page for more). In this type of quoted string, \\ represents a literal backslash. So the program passed to sed is actually

1 i\
name    age     university      city

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

$ { 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

Tags:

Linux

Unix

Awk

Sed

Cat