How to search for a word in column header that fully matches the word not partially in awk?

I have a multicolumn text file with header in the first row like this

The headers are stored in an array called

. which contains

I want to search for each elements of this

array from that multicolumn text file. And I am using this awk approach

for ii in ${hdr[@]}
do

gawk -vcol="$ii" -F $'\t' ' 
$0 ~ col{
for(s=1;s<=NF;s++){ 
heading=$s 
colhdr=heading
if(index(heading, col))wanted=1
}
}
'

done

But this gives me both

and

columns while searching for

. How can I only read

column?
For example if I search

it should return column number 1 but my script is returning 1 and 2, which is wrong.

Not sure where to begin... - OK, let's try:

You're missing the multicolumn text file as an input to awk , so it doesn't know what to operate on.
Your awk code doesn't have a print statement, so nothing will be printed. So your result of 1 or 2 is a bit surprising. If it printed something, then the (desired) result for the given contents of hdr array should be 2 and 4, for the two elements as indicated.
Your pattern check $0 ~ col is quite unspecific, it will trigger on any occurrence of the pattern also later in the file - you may want to confine the action to the first line only.
It's not clear what the heading , colhdr , and wanted variables / arrays are meant for, as they aren't used anywhere.
You want a "word in column header that fully matches the word not partially", so why use the index function in lieu of an equals operator?

How far wqould this get you:

for ii in ${hdr[@]}
  do    awk -vcol="$ii" ' 
        NR == 1 {for (s=1; s<=NF; s++)  if ($s == col) print s
                }
        ' file
  done
2
4
1 Like