Explain this awk

found this handy one liner in another thread which is closed, it does what i need but im trying to understand it. it basically matches the field that contains the value v and prints its position

awk -F, '{for(i=1;i<=NF;i++)if($i==v)print i}' v=yourfield inputfile

my understanding is assign loop through the inputfile until the total number of fields has been reached, if the contents of i matches the pattern, print the number i which would be the position number.

would appreciate if someone could express above in a more eloquent manner! thanks

It means for every line: loop through the fields, if a field matches the variable v then print the field position.

This script seems a bit strange to me, since it will just produce field numbers that cannot be related to the line numbers in the input file.

For example:

$ printf "ape,dog,cat,dog\ndog,snake\n"  | awk -F, '{for(i=1;i<=NF;i++)if($i==v)print i}' v=dog
2
4
1
1 Like
awk                 # obviously
-F,                 # use comma as the field seperator
'{                  # begin code to run
for(i=1;i<=NF;i++)  # loop over fields in record maintaining position in index "i"
   if($i==v)print i # if the value at the current position is the desired value print the current position
}'                  # end of code to run
v=yourfield         # set the desired value
inputfile           # set the file to iterate over
1 Like

thanks.

yes it is strange in its current form, I had to tweak it as i was only feeding the header.