kllrdr
kllrdr

Reputation: 177

Compare column 2 between two files and print the output with all other columns

I would like to compare two files based on column 2 and print all other columns in the output.

File 1:

p1 p2 rg se p
F Fht 0.3 0.01 0.05
F Tom 0.01 0.004 0.34

File 2:

p1 p2 rg se p
M Fht 0.2 0.02 0.06
M Ram 0.03 0.004 0.32

Desired output:

p1 p2 rg se p p1 p2 rg se p
M Fht 0.2 0.02 0.06 F Fht 0.3 0.01 0.05

I figured out how to print the difference out, but not the common columns.

awk 'NR==FNR{++a[$2];next} !($2 in a)' file1 file2

Upvotes: 1

Views: 970

Answers (1)

anubhava
anubhava

Reputation: 785156

You may use this awk:

awk 'NR == FNR {map[$2] = $0; next} $2 in map {print $0, map[$2]}' f1 f2 | column -t

p1  p2   rg   se    p     p1  p2   rg   se    p
M   Fht  0.2  0.02  0.06  F   Fht  0.3  0.01  0.05

I used column -t for tabular output here.

Upvotes: 1

Related Questions