Search code examples
awk

Print column contents by column name


I want to input a string name (i.e. "COL2") to an awk or cut command and print the column that matches that column header string.

the datafile looks like this:

COL1 COL2 COL3 COL4 COL5 COL6
a a b d c f
a d g h e f
c v a s g a

If I pass in COL3, I want it to print the third column, etc. I'm thinking awk might be the easiest thing to use, but cut may also work. I'm just not sure how to go about doing this.


Solution

  • Awk 1 liner for above problem (if you are interested):

    awk -v col=COL2 'NR==1{for(i=1;i<=NF;i++){if($i==col){c=i;break}} print $c} NR>1{print $c}' file.txt
    
    awk -v col=COL3 'NR==1{for(i=1;i<=NF;i++){if($i==col){c=i;break}} print $c} NR>1{print $c}' file.txt
    

    Just pass your column name COL1, COL2, COL3 etc with -vcol= flag.