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.
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
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
perl -i -lne 'if($.==1){print "newline\n$_"}else{print}' your_file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With