How to compare 2 columns in 2 different files and print corresponding line if the column matches

I have 2 huge files with >8k lines.

file 1:

porta side1 13 23
portb side1 56 76
portc side2 67 76
.
.

file 2:

porta side1 11 45
portb side3 50 72
portc side2 56 66
.
.

column 1 in both files are same. I want to compare column 2 in both files and if it is same, I need the line to be printed required output:

porta side1 13 23
portc side2 67 76

I tried it with awk, but output is complete file1 (it also prints portb)

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

Please help me to correct it to get the required output also I tried to paste both files together and then comparing the columns:

paste file1 file2 > mergefile
awk '{if ($2=$6) { print $0 } }' mergefile 

the output is again not the required one. It prints same mergefile with updating column2 ($2) with value in $6. Please help with a solution here. Thanks

Upvotes: 0

Views: 45

Answers (1)

Ed Morton
Ed Morton

Reputation: 204477

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

Upvotes: 2

Related Questions