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?
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.
“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.
In awk, $0 is the whole line of arguments, whereas $1 is just the first argument in a list of arguments separated by spaces.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With