0

I am looking for a way to compare column $2 and column $1 of two files and if they are the same than print all columns from the first file with column $2 from the second file.

file_1.txt

apple    tree    5
great    see     10
see      apple   3
tree     bee     11
make     change  2

file_2.txt

apple    5.21      
around   6.21      
great    2         
bee      1         
see      7.43      
tree     3         

The output should look like:

apple    tree    5    3     
great    see     10   7.43
see      apple   3    5.21
tree     bee     11   1   

I tried

awk 'NR==FNR{a[$2];next} ($1 in a) {print}' file_1.txt file_2.txt > output.txt

which obviously just prints the matching lines of file_2.txt. So how do I add the print statement for the columns of the 1st file?

I tried to read in more columns in an array like

awk 'NR==FNR{a[$2];b[$1];c[$3];next} ($1 in a) {print a, b c}' file_1.txt      file_2.txt > output.txt

which is obviously wrong ;)

Help is very much appreciated.

2
  • Only awk? no other langs? Feb 17, 2017 at 11:02
  • I do not mind other languages, as long as it produces the output ;) so every help is appreciated Feb 17, 2017 at 11:06

1 Answer 1

2

How about

$ awk 'NR==FNR {a[$1]=$2; next} $2 in a {print $0, a[$2]}' OFS='\t' file_2.txt file_1.txt 
apple  tree   5   3
great  see    10  7.43
see    apple  3   5.21
tree   bee    11  1
1
  • great, this is it! thank you so much! it is perfect! Feb 17, 2017 at 11:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .