Add a header to a tab delimited file

让人想犯罪 __ 提交于 2019-11-28 21:53:28

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

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;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!