Reputation: 4099
Below are my two files' content:
cat f1
9
5
3
cat f2
1
2
3
This is my code, which works perfectly and gives output as per my understanding:
awk 'NR==FNR {a[$0]; next} FNR in a' f1 f2
3
But, when I swap the position of these 2 argument files, the output is different than what I expected.
awk 'NR==FNR {a[$0]; next} FNR in a' f2 f1
9
5
3
I expected the output as 3 again as like previous, because f2 and f1 both has exactly 3 lines and the key 3 is however stored in the hash map. Please explain how the 2nd code works.
Upvotes: 0
Views: 29
Reputation: 754410
The output from the second example is, of course, correct.
Since f2
contains the values 1, 2, 3, the array a
ends up with elements a[1]
, a[2]
, and a[3]
. When it is processing f1
, line 1 has FNR == 1
, and 1
is an index in a
, so line 1 (containing 9
) is printed; similarly for lines 2 and 3, hence the output you see.
Upvotes: 1