find the field number

######################## SOLVED ##################

Hi

I have a header file like the following and the field "IDENTIFIER" can be at any possition on this line,
The line can containt a variable number of field, not alway the same depending of the header file i use

 
BAS,FastZeroSurfUNIT,ZeroSurfCAL,FastZeroSurfDAYC,IDENTIFIER,FunctionIdFLAG
 

I try to write a fonction that will return me the position of the collum "IDENTIFIER"

any idea ?

How does the file look like?

the file is compose of one line the following

BAS,FastZeroSurfUNIT,ZeroSurfCAL,FastZeroSurfDAYC,IDENTIFIER,FunctionIdFLAG

what i am trying to do, is to create a array of the line, then test the array in order to find the position of the field = IDENTIFIER

so on my example output would be

echo "the field IDENTIFIER is on position $pos"
the field IDENTIFIER is on position 5

Try:

awk -F, '{for(i=1;i<=NF;i++)A[$i]=i;print "The field "v" is on position "A[v];delete A}' v=IDENTIFIER infile

or without arrays:

awk -F, '{for(i=1;i<=NF;i++)if($i==v)print "The field "v" is on position "i}' v=IDENTIFIER infile
2 Likes

hi

this commande doesn't work, and how do you check that the A[$1]=IDENTIFIER

 
awk -F, '{for(i=1;i<=NF;i++)A[$i]=i;print "The field "v" is on position "A[v];delete A}' FastZero_header.csv
 Syntax Error The source line is 1.
 The error context is
                {for(i=1;i<=NF;i++)A[$i]=i;print "The field "v" is on position "A[v];delete >>>  A} <<<
 awk: 0602-502 The statement cannot be correctly parsed. The source line is 1.

 
perl -F, -lane'BEGIN {
    $f = shift
 } 
    $F[$_] eq $f 
   and print "The field $f is on position ", ++ $_
        for 0 .. @F
  ' IDENTIFIER infile

---------- Post updated at 04:02 PM ---------- Previous update was at 03:55 PM ----------

delete <array_name> is a GNU awk extention.
With most other awk implementations you could use split("", <array_name>) with the same effect.

2 Likes

Thanks the probleme is solve thanks a lot
both solution work fine the perl one and the awk one

Is used the awk, i just undertand it better
here is the final line i used

export POSITION=`grep "IDENTIFIER" FastZero_header.csv | awk -F, '{for(i=1;i<=NF;i++)if($i==v)print i}' v=IDENTIFIER`

Thanks all