Reputation: 153
I found the below command works. But could someone explain me what it actually does?
awk 'NR==FNR{a[NR]=$2; next} {print a[FNR], $2}' file1 file2
It extracts the fields passed in the command from the files and display it in the terminal.
Upvotes: 0
Views: 44
Reputation: 289765
awk 'NR==FNR{a[NR]=$2; next} {print a[FNR], $2}' file1 file2
As NR
stands for Number of Record and FNR
for Record Number in the current input File, they are equal when processing the first file. Hence, awk 'NR==FNR { things1; next } { things2 }' file1 file2
means:
things1
when processing the first file. things2
when processing the second file.a[NR]=$2; next
means:
a[]
with the index being the number of record (number of line, generally, like in this case).print a[FNR], $2
means:
This way, this will produce an output consisting in the 2nd field of both files, side by side.
$ cat f1
1 2 3
4 5 6
7 8 9
10 11 12
$ cat f2
a1 a2 a3
a4 a5 a6
a7 a8 a9
a10 a11 a12
$ awk 'NR==FNR{a[NR]=$2; next} {print a[FNR], $2}' f1 f2
2 a2
5 a5
8 a8
11 a11
You can find more information in Idiomatic awk.
Upvotes: 1