Hi Guys,
I have a question on how i can get the column number in a file and used it in awk.
i have a file which it has these records inside it.
SUB_ACC_NO|CLIENT_ID|ANUM|AKEY|ACCT_TYPE|FUND_ID|FUND_ABBR|TRADER_ID|TRADER_NAME|BROKER|VARIABLE_FIELDS_PRIMARY|CURRENCY|CLIENT_FUND_ID|ANAME|CASH_ANUM|ANUM_GROUP|VALUE_DATE|BALANCE|CUR_BALANCE|TRAN_STATUS|TRAN_TYPE|STMT_PG|SIDE|SIGN|REC_TYPE|BALANCE_TYPE|GIN2CXL|ETL_DATE
and there are other files that have the same header name but with different positions. what i wanted to achieve is to get the column number for the header field that starts with SUB_ACC_NO.
thanks
NF
is the number of fields in a line. You can walk across all of them to see if it equals SUB_ACC_NO like so:
$ awk -F\| '{ for (i=1;i<=NF;i++) if ($i == "SUB_ACC_NO") print i }' input
1
Since we only care about line 1 (where headers are), then use the condition NR==1
or you can exit early NR>1{exit}
awk -F\| 'NR>1{exit}1{ for (i=1;i<=NF;i++) if ($i == "SUB_ACC_NO") print i }' input
awk -F\| 'NR==1{ for (i=1;i<=NF;i++) if ($i == "SUB_ACC_NO") print i }' input
Or more simply:
awk -F '|' '
{ for(i = 1; i <= NF; i++)
if($i == "SUB_ACC_NO") {
print i
exit
}
}' input
1 Like
Or simply
$ awk '$1 == "SUB_ACC_NO"{print NR;exit} ' RS="|" file
1 Like
Simply, but that's not the question, please reread the OP.
@Franklin52 I didn't get you. will you please explain me what went wrong..
Sorry, I didn't noticed the RS in your solution.
It's all right, it happens.