Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print column contents by column name

Tags:

awk

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.

like image 828
Nick Avatar asked May 01 '11 03:05

Nick


1 Answers

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.

like image 147
anubhava Avatar answered Oct 17 '22 22:10

anubhava