Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a header to a tab delimited file

Tags:

linux

unix

sed

awk

cat

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.

like image 729
Dnaiel Avatar asked Oct 15 '12 19:10

Dnaiel


4 Answers

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
like image 111
newfurniturey Avatar answered Nov 11 '22 00:11

newfurniturey


$ { 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
like image 24
William Pursell Avatar answered Nov 10 '22 22:11

William Pursell


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
like image 6
David Z Avatar answered Nov 10 '22 23:11

David Z


perl -i -lne 'if($.==1){print "newline\n$_"}else{print}' your_file
like image 3
Vijay Avatar answered Nov 10 '22 22:11

Vijay