问题
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.
回答1:
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
回答2:
$ { 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
回答3:
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
回答4:
perl -i -lne 'if($.==1){print "newline\n$_"}else{print}' your_file
回答5:
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
回答6:
cat <(head -1 theFileWithHeader) theFileWithoutHeader > newfile;
mv newfile theFileWithoutHeader;
来源:https://stackoverflow.com/questions/12902497/add-a-header-to-a-tab-delimited-file