2

I have one document, and this document has several columns, like this:

,Flag2,,Flag4,Flag5,,,,,Flag10,Flag11,Flag12,Flag13

If I use awk to know the total number of fields, knowing the separator character is , the result is: 13

Now, I want to get the field number for Flag10, the result should be: 10

How can I do this with awk?

3

You could do like below,

awk -F, '{for(i=1;i<=NF;i++)if($i=="Flag10")print i}' file

Example:

$ echo ',Flag2,,Flag4,Flag5,,,,,Flag10,Flag11,Flag12,Flag13' | awk -F, '{for(i=1;i<=NF;i++)if($i=="Flag10")print i}'
10
3

To use awk builtin's:

awk -F, -v field="Flag10" '{sub(field",.*",field);print split($0,any)}' doc.file

The script will remove everything after the first occurrence of the value of field (in this case, Flag10) and then print the result of splitting the line on commas. Since we've deleted everything after Flag10, this results in the number of fields left which is the field number of the search pattern.

0
2

I typically create an associative array, mapping the header names to the column numbers

awk -F, -v head="Flag10" '
    FNR == 1 {for (i=1; i<=NF; i++) col[$i] = i}
    {print $col[head]}
' << END
,Flag2,,Flag4,Flag5,,,,,Flag10,Flag11,Flag12,Flag13
10,20,30,40,50,60,70,80,90,100,110,120,130
END
Flag10
100

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.