0

I wrote a simple function in bash to search the first line of a CSV file and return the column number of a matching header value:

findcolnum()
{
    colnum=`head -1 $1 | awk -F"," '{for(i=1;i<NF;i++) if($i==$2) {print i}}'`
    echo $colnum
}

When I make the call to the function:

analogcol=`findcolnum "$DIR/PCICCP_AnalogPoint_DMS.csv" "AnalogPointRef"`

The result is always "2" no matter whether the column exists or not.

While on command line, where I tested the command before putting it into a script, it is returning the correct value:

head -1 Outbox/ICCP/PCICCP_AnalogPoint_DMS.csv | awk -F"," '{for(i=1;i<NF;i++) if($i=="AnalogPointRef") {print i}}'
9

Can anyone help me understand what's going on here?

b w
  • 91
  • 1
  • 5
  • `$2` inside `awk` doesn't refer to your external variable, but to a temporary variable inside `awk` –  Nov 09 '17 at 02:53
  • 1
    Untested, but try `colnum=\`head -1 $1 | awk -F"," '{for(i=1;i –  Nov 09 '17 at 02:54
  • Thanks a lot guys. I will play around with it to figure it out. Also, off-topic but, my name is Benjamin W as well haha... – b w Nov 09 '17 at 03:05
  • @bw Ha! There are apparently more than 100 of us on Stack Overflow ;) https://stackoverflow.com/users?page=1&tab=reputation&filter=week&search=benjamin+w – Benjamin W. Nov 09 '17 at 03:12
  • Rather than going to the trouble of doing `colnum=`head -1 $1 | awk -F"," '{for(i=1;i – rici Nov 09 '17 at 03:20
  • Also in addition to the [useless `echo`](http://www.iki.fi/era/unix/award.html#echo) you could avoid the separate `head` with `awk -F , 'NR==1{ for(i...` – tripleee Nov 09 '17 at 05:13

0 Answers0