Add a header to a tab delimited file

前端 未结 8 839
北恋
北恋 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:31

    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...
    $
    
    
    0 讨论(0)
  • 2020-12-14 22:33
    perl -i -lne 'if($.==1){print "newline\n$_"}else{print}' your_file
    
    0 讨论(0)
  • 2020-12-14 22:45

    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
    
    0 讨论(0)
  • 2020-12-14 22:45
    cat <(head -1 theFileWithHeader) theFileWithoutHeader > newfile;
    mv newfile theFileWithoutHeader;
    
    0 讨论(0)
  • 2020-12-14 22:48
    $ { 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
    
    0 讨论(0)
  • 2020-12-14 22:51

    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
    
    0 讨论(0)
提交回复
热议问题