3

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?

5

Try this:

$ awk 'FNR==NR{a[$1]=$0;next};{print a[$1]}' file2 file1
  • 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
1

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

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.