Add a header to a tab delimited file

前端 未结 8 840
北恋
北恋 2020-12-14 21:46

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:



        
相关标签:
8条回答
  • 2020-12-14 22:51

    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
    
    0 讨论(0)
  • 2020-12-14 22:51

    Customary awk answer.

    awk 'BEGIN { print "name\tage\tuniversity\tcity" } { print }' yourfile > /tmp/out && mv /tmp/out yourfile
    
    0 讨论(0)
提交回复
热议问题