Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are NR and FNR and what does "NR==FNR" imply?

Tags:

awk

I am learning file comparison using awk.

I found syntax like below,

awk 'NR==FNR{a[$1];next}$1 in a{print $1}' file1 file2 

I couldn't understand what is the significance of NR==FNR in this? If I try with FNR==NR then also I get the same output?

What exactly does it do?

like image 907
Amit Avatar asked Sep 09 '15 14:09

Amit


People also ask

What does NR mean in Linux?

NR: NR command keeps a current count of the number of input records. Remember that records are usually lines. Awk command performs the pattern/action statements once for each record in a file. NF: NF command keeps a count of the number of fields within the current input record.

What does NR stand for in awk?

“NR” is a special built-in variable of AWK that stands for “number of records”. This variable is used to deal with the number of records present in the specified files.

What awk $0?

In awk, $0 is the whole line of arguments, whereas $1 is just the first argument in a list of arguments separated by spaces.

What does next do in awk?

The next statement forces awk to immediately stop processing the current record and go on to the next record. This means that no further rules are executed for the current record, and the rest of the current rule's action isn't executed.


1 Answers

In awk,

FNR refers to the record number (typically the line number) in the current file,
NR refers to the total record number.
The operator == is a comparison operator, which returns true when the two surrounding operands are equal.

This means that the condition NR==FNR is only true for the first file, as FNR resets back to 1 for the first line of each file but NR keeps on increasing.
This pattern is typically used to perform actions on only the first file.

The next inside the block means any further commands are skipped, so they are only run on files other than the first.

The condition FNR==NR compares the same two operands as NR==FNR, so it behaves in the same way.

like image 84
Tom Fenech Avatar answered Oct 12 '22 13:10

Tom Fenech