Print column contents by column name
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.
Note that the first solution prints out the whole file if the named column does not exist. To output a warning message if this occurs try
awk -v col=NoneSuch 'NR==1{for(i=1;i<=NF;i++){if($i==col){c=i;break}} if (c > 0) {print $c}} else {print "Column " col "does not exist"} NR>1 && c > 0 {print $c}' file1.txt
a slight modification of anubhava post on top, for multiple columns
awk -vcol1="COL2" -vcol2="COL6" 'NR==1{for(i=1;i<=NF;i++){if($i==col1)c1=i; if ($i==col2)c2=i;}} NR>0{print $c1 " " $c2}' file.txt
when NR>1 does not print the column headers. This was modified to NR>0 which should print the columns with header names.