Q:

awk scripting for simulation

hai friends good evening to all
i am the beginner to awk so i request you to please help me 
i want to print total number of records(rows) in a text file.for that i use "print NR "command.when i use this command on BEGIN block it prints number of records instead of printing total.but when we use it in END block it returns total number of records.
for example i have a text file with 5 column and i tried like this
BEGIN {
print NR
} it returns 
1
2
3
4
5
i want to print total number of records(rows) from BEGIN block itself,so please give me the answer.

A:

NR is populated/incremented as the files are read, BEGIN is executed before any file is opened, so what you're specifically asking for can't be done.
A workaround is this:
awk 'BEGIN{ while ( (getline var < ARGV[1] > 0) ) nr++; print nr }' file

but on UNIX there are simpler ways if your records are newline-separated, e.g.:
awk -v nr="$(wc -l < file)" 'BEGIN{ print nr }' file

Also just in awk you could probably get the output you want using:
awk 'NR!=FNR && FNR==1 { print NR - FNR }' file file

