Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


aaa 23 3
bbb 56 6
ccc 45 2


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

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 '14 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]}=$_;
                  while(<A>){/^(.+?)\s/; print $k{$1}}
               }' file2
aaa a m
bbb m a
ccc m m
share|improve this answer

Your Answer


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.