Print column postion

Hi,

I am using the below code for printing the column position of a particular string

nawk -v srch="DName" -F '\t' '{for(j=1; j<=NF; j++) { if($j==srch) print j } exit }' input_file.txt

The above code prints the column position of the input string DName (that is 1)

Now the problem is, the above code is working fine for the data that starts from 1st line in a tab delimited file, but it is not working for files where the data is starting from 2 or 3 rd row.

Can anybody plz help.

Thanks

Please provide representative examples how your input file can look like

$ awk 'match ($0, srch) {print NR, RSTART; exit}' srch="DName" file

There is no need of exit here!!!

exit makes the command to stop processing after the first row.

Hi,

its working for the below code

$ awk 'match ($0, srch) {print NR, RSTART; exit}' srch="DName" file

The sample data of my input file looks like:
ACCENT_INPUT

Pcode    Dealer Name    Comp    INF    Date    Year    
TN16 9BE    Ambrose Fisher Ltd    Franklin UK Mid Cap Fund A Inc GBP    GB00B3ZGH246    5/31/2012    2012  (starts from 2nd row
TN16 9GF    Baggette and Company Wealth Management Limited    Templeton Global Bond A Mdis GBP H1    LU0316492692    5/31/2012    2012

Thanks

---------- Post updated at 08:45 AM ---------- Previous update was at 08:29 AM ----------

in the same way, plz let me know if it is possible to insert a dummy column (column has a header but no data) in nth position?

Thanks

---------- Post updated at 08:48 AM ---------- Previous update was at 08:45 AM ----------

The below code works for data starting from 1st row

nawk -v p="2" -v col="Dummy" ' {BEGIN { FS=OFS="\t" } { NR==$0?$p=col"\t"$p:$p="\t"$p } } 1 ' input_file.txt> temp_file.txt

but not for data starting from 2 or 3 row

You need a criteria to determine at which line your data start.

Since we do not know how your input files can look like (we only have few examples) we can't guess which generic rule should be chosen so that it would work for all the different input you can have.

Could we assume that your data always start at the first lines beginning with "TN" ?

There is no particular pattern for the data, it could be in any format and start at any row.
Is it possible to get the line number where the column header starts, atleast

Thanks

---------- Post updated at 09:26 AM ---------- Previous update was at 09:22 AM ----------

how about this?

 nawk 'NR>1{print NR; exit}' input_file.txt

but the result is 2, whereas the data is starting from line 3

thanks

In the original solution by OP there were a couple of braces in the wrong place:

$ awk -F '\t' '{for(j=1; j<=NF; j++) if($j==srch) {print j; exit } }' srch=GB00B3ZGH246 file
4