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.

  • Only awk? no other langs? – Jacob Vlijm Feb 17 '17 at 11:02
  • I do not mind other languages, as long as it produces the output ;) so every help is appreciated – dani_anyman Feb 17 '17 at 11:06
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
  • great, this is it! thank you so much! it is perfect! – dani_anyman Feb 17 '17 at 11:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.