Frog
Frog

Reputation: 39

How to search for each elements of an array in a text file?

I have an array called headers. echo ${headers[@]} returns A B C D. I want to search for each of these elements from the first line of a text file and returns the column number where it is situated.

A sample input file could be like this

T   A  Z   R   B  E   C  D
10  1  5   0   5  88  0  8
20  8  2   10  2  10  1  45
30  2  33  11  8  25  2  40 
40  7  0   1   1  87  3  96

I made a loop over the elements of that array and tried to feed it into a gawk. But somehow it is not searching for those elements in the array.

This is my snippet

for ii in ${headers[@]}
do
   echo $ii

  gawk -vtoken="$ii" -F  $'\t' '                                 
     /$token/{                     # This is the line where I tried to feed the element of the header array.                                
        for(f=1;f<=NF;f++){                        
           hdr=$f                                  
          colhdr[f]=hdr                            
          if(index(hdr,"$token"))wanted[f]=1
        }
     } ' inputfile.txt


done

Upvotes: 1

Views: 124

Answers (1)

Ed Morton
Ed Morton

Reputation: 204208

Is this what you're trying to do?

$ cat tst.awk
NR==1 {
    split(headers,tmp)
    for (i in tmp) {
        hdrs[tmp[i]]
    }
    for (i=1; i<=NF; i++) {
        if ($i in hdrs) {
            print $i "=" i
        }
    }
    exit
}

$ headers=(A B C D)

$ awk -v headers="${headers[*]}" -f tst.awk file
A=2
B=5
C=7
D=8

Upvotes: 1

Related Questions