Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to compare two files based on the value of their first column:

file1

aaa 23 3
bbb 56 6
ccc 45 2

file2

bbb m a
aaa a m
ccc m m

The output file should be:

aaa  a m
bbb  m a
ccc  m m

i.e., we need to print the 2nd and 3rd columns of the 2nd file with the first column order of first file.

Can anybody suggest an awk script for this?

share|improve this question

2 Answers 2

Try this:

$ awk 'FNR==NR{a[$1]=$0;next} {print a[$1]}' file2 file1
share|improve this answer
    
thank u... the code is working... i made little modifications to get the proper result....thank u so much –  Rincy Raphael Jul 7 at 6:09

This will be very slow for large files, but you could do

$ while read a rest; do grep -w $a file2; done < file1
aaa a m
bbb m a
ccc m m

A faster way, in Perl:

$ cat file1 | perl -lane '$k{$F[0]}=$_;
                END{
                  open(A,"file1");
                  while(<A>){/^(.+?)\s/; print $k{$1}}
               }' file2
aaa a m
bbb m a
ccc m m
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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