determining column number using string in awk

It feels a little bit clumsy but I always find the column numbers using the following line of code:

head -1 file | sed 's/delimiter/\n/g' | nl
Here I take the header row of the file and pipe it to sed replacing the delimiter with \n. The result is that every column header is now on a new line. Finally I pipe this to nl which adds row numbers which correspond to the original column numbers.


You can try:

$ awk -F'|' '
{
  for(i=1;i<=NF;i++) {
    if($i == "Fruits")
      printf("Column %d is Fruits\n", i-1)
    if($i == "Colors")
      printf("Column %d is Colors\n", i-1)
  }
  exit 0
}
' file
Column 2 is Fruits
Column 3 is Colors

A note that the actually column for Fruits and Colors are $3 and $4.


Maybe it is better to print all the columns present in the first row, in order to check not only for these two fields, but also detecting new columns, their names, order changes, etc.

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

output:

1
2 Sr
3 Fruits
4 Colors
5

Tags:

Bash

Awk