Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

FNR variable

Status
Not open for further replies.

ranjit

Technical User
Apr 14, 2000
131
GB
[tt]
Dear all,

What is the purpose of the NR==FNR statement in the short routine below:

# cat file
10
20
30

# cat data
AA
AA
AA
AA
AA
10 - line1
10 - line2

# nawk 'NR==FNR{a[$1]=$1;next}a[$1]' file data
10 - line1
10 - line2
[/tt]
 
Hi

I think the man page explains it clearly :
man awk said:
FNR The ordinal number of the current record in the current file.

NR The ordinal number of the current record from the start of input.
So [tt]NR[/tt] counts the lines from the very begining countinuously until the end. [tt]FNR[/tt] restarts the counting at the begining of each input file.

So the [tt]NR==FNR[/tt] expression evaluate to true only while the first input file is parsed.

Feherke.
 
NR is the Number of the current Record (line) being processed.
FNR is the Number of the current Record within the current file.

So, for the first file processed they will be equal but on the first line of the second and subsequent files FNR will start from 1 again.

In the example code, when NR==FNR (i.e. when processing the first file) an associative array is built up storing the first field in an array element which also has the first field as its index.

next means nothing else is done with this line from the first file.

when NR!=FNR (i.e. when processing the second and subsequent files) the associative array is checked to see if it has an element indexed by the first field and if so the default behaviour (of printing out all of the line being processed) is carried out.

==========================================
toff.jpg
Some cause happiness wherever they go; others whenever they go.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top