Lets sat my file1 is:

A   S   
B   Q

file2 is:

B   2

I want to match $1 from file2 with $1 file1 and print file1 $2 && file2 $2, for the output like this:

Q   2    

My awk solution is:

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

And it gives me only Q - it doesn't print array's second element.
How can I print array's element?


I updated my question as the answer that works for dummy example doesn't work with my actual data.

chr2    47558199    ENSG00000236824.1 
chr2    47558199    ENSG00000236824.1 
chr2    47558199    ENSG00000236824.1 

ENSG00000236824.1   AAAAAAA

I want to match f2 $1 with f1 $3 and print f1 $0 plus f2 $2

I tried this answer awk 'NR==FNR {a[$1]=$2;next} $3 in a {print $0, a[$1]}' f2 f1,
but still not getting the output I want.

awk code above gets me only this:

chr2    47558199    ENSG00000236824.1 
chr2    47558199    ENSG00000236824.1 
chr2    47558199    ENSG00000236824.1 

You were almost there. Just change the array index to $1 – that is the common element of both files:

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

And no idea why you put $1$2 in the array, as you seem to need only $2.

Update according to the question edit.

You clearly put that “match f2 $1 with f1 $3” (I wish every question to be so clear) so just write it in the code accordingly:

              f2 $1                             f1 $3
                |                                 |
awk 'NR==FNR {a[$1]=$2;next} $3 in a {print $0, a[$3]}' f2 f1
  • Can you please check updated question as answer doesn't seem to work with my actual data. – PoGibas Jun 20 '13 at 15:33
  • So we are saying: a[$1] - put in array f2 $1; if f1 $3 is in array (that is f2 $1), then print. But 1) why do we need =$2 ; 2) How do we make f2 $2 encoded as a[$3]? – PoGibas Jun 20 '13 at 16:30
  • OK, when we says $3 in a it puts f2 $2 into that position, hence to print it we have to say "print position $3". – PoGibas Jun 20 '13 at 16:33
  • I think you got it. A generic advice: when confused, dump your variables' values. For example you can put something like this in your script END{for(i in a)printf"a[ %s ] = %s\n",i,a[i]} to list the indexes and values in array a. As with you current code $0 is already listed in the output just above END, should be clearly visible what to use as array index to get the corresponding values. – manatwork Jun 20 '13 at 16:42

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.