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:
Using sed
no need of temp file
sed -i "s#^#name\tage\tuniversity\tcity#g#"
Demo:
$ cat file1.txt
roger\t18\tcolumbia\tnew york\n
albert\t21\tdartmouth\tnew london\n
etc...
$ sed -i "s#^#name\tage\tuniversity\tcity#g#" file1.txt $ cat file1.txt
name age university cityroger\t18\tcolumbia\tnew york\n
name age university cityalbert\t21\tdartmouth\tnew london\n
name age university cityetc...
$
perl -i -lne 'if($.==1){print "newline\n$_"}else{print}' your_file
First create a file with the header content:
$ cat >header
name^Iage^Iuniversity^Icity (return)
^D
(where ^I
is the tab key)
Then prepend it to the data
$ cat header myfile >newfile
$ mv newfile myfile
cat <(head -1 theFileWithHeader) theFileWithoutHeader > newfile;
mv newfile theFileWithoutHeader;
$ { 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
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