LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   NR versus FNR in awk scripts (https://www.linuxquestions.org/questions/linux-newbie-8/nr-versus-fnr-in-awk-scripts-4175534483/)

Upendra Pratap Singh 02-18-2015 10:44 PM

NR versus FNR in awk scripts
 
I have got a data file that contains 22 records.

When i write an awk script to compute the number of records, i print the value of NR variable. Why does it show 23 instead of 22?

I get the same output from FNR variable also. So what is the difference between NR and FNR variable?

In the text i found that
NR: gives number of records read- record number in the current file
FNR: file number of records read- a record number in the current file

grail 02-18-2015 11:47 PM

This may be clearer on the difference:
Quote:

The awk utility divides the input for your awk program into records and fields. awk keeps track of the number of records that have been read so far from the current input file. This value is stored in a built-in variable called FNR. It is reset to zero when a new file is started. Another built-in variable, NR, records the total number of input records read so far from all data files. It starts at zero, but is never automatically reset to zero.
As for the different number of records, you will need to explain further what you mean by '22 records'?
Also, remember that awk reads every line of the file so if any line is blank it is still a record according to awk.

Upendra Pratap Singh 02-19-2015 12:50 AM

22 records meant that there was a single column with 22 rows. these rows were containing age values.

example:
23
33
44
65
54 etc. there were 22 such values one in each row

If NR value starts from 0 then for 22 such values read, the final value should be 21. why am i getting 23 then?

grail 02-19-2015 07:59 AM

Well firstly, NR starts at 1 for the first line. Assuming that there are no blank lines, can you also confirm the file was not created on a windows machine?

If not created on windows, you would need to provide the data and the awk command you are using.


All times are GMT -5. The time now is 05:48 AM.