Koushic
Koushic

Reputation: 153

How to extract fields from 2 different files and store in an output file using shell script?

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

Answers (1)

fedorqui
fedorqui

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:

  • do things1 when processing the first file.
  • do things2 when processing the second file.

a[NR]=$2; next means:

  • store the 2nd field in the array a[] with the index being the number of record (number of line, generally, like in this case).

print a[FNR], $2 means:

  • print the corresponding stored field from the previous file together with the 2nd field from the current file.

This way, this will produce an output consisting in the 2nd field of both files, side by side.

Test

$ 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

Related Questions