Need help with using a script variable in awk

Hi All,

Please help me with a issue in below code

head -1 sample.txt > header.txt
field_count=`head -1 sample.txt |  tr -dc '\t' | wc -c`
field_count=`expr $field_count + 1`
i=1
while [ $i -lt $field_count ]
do
j=`expr $i + 1`
field_name[$i]= `awk -F\t 'NR>=1{print ${$j}}' header.txt`
echo ${field_name[$i]}
i=`expr $i + 1`
done

I have issue with the awk statement , the last echo statement.

My requirement: to store the headers from tab delimited file into an array and print them
Note: I dont know how many headers my input file may have.

Regards,
Ajay

Can you give us a representative sample content of file: sample.txt and desired output?

You can achieve this with eval.
Try this:

head -1 sample.txt > header.txt
field_count=`head -1 sample.txt |  tr -dc '\t' | wc -c`
field_count=`expr $field_count + 1`
i=1
while [ $i -lt $field_count ]
do
j=`expr $i + 1`
CMD="awk -F\t 'NR>=1{print \$$j}' header.txt"
field_name[$i]=`eval $CMD`
echo ${field_name[$i]}
i=`expr $i + 1`
done

What shell is that? Bash is as easy as:

mute@clt:~/temp$ cat sample.txt
first_name      last_name       street1 city    state   zip
neutron scott   123 e main st   ca      90210
mute@clt:~/temp$ ./headers
declare -a field_names='([0]="first_name" [1]="last_name" [2]="street1" [3]="city" [4]="state" [5]="zip")'
mute@clt:~/temp$ cat headers
#!/bin/bash

IFS=$'\t' read -ra field_names < <(head -1 sample.txt)

declare -p field_names