printing 3 files side by side based on similar values in rows

Hi I'm trying to compare 3 or more files based on similar values and outputting them into 3 columns.

For example:
file1
ABC
DEF
GHI

file2
DEF
DER

file3
ABC
DER

The output should come out like this

file1     file2     file3
ABC              ABC
DEF    DEF         
GHI
           DER    DER

I know how to merge the 3 files into one but I don't know how to get the logic needed to output the above.

Matches your example, maybe should be adapted to your exact needs :
#!/bin/bash
cat file{1..3} | sort -u | while read
do
for F in file{1..3}; do
printf "%-10s" "$(grep "$REPLY" $F)"
done
echo
done

Output:

ABC                 ABC       
DEF       DEF                 
          DER       DER       
GHI

Working on it for you in perl.

Do the files have the same number of lines in them and are there any commas, tabs, or special characters within the files? Thanks, John

---------- Post updated at 03:52 PM ---------- Previous update was at 03:31 PM ----------

If you still need a solution, let me know. However, it looks like frans has a shorter solution than my perl script. jjarrettc

Thanks a lot for your help guys! I'll try to customize it to fit what i need

my $n=0;
my @tmp = glob("*.txt");
for(my $i=0;$i<=$#tmp;$i++){
  my $file = $tmp[$i];
  open FH,"<$file";
  while(<FH>){
    chomp;
    if(exists $hash{$_}){
     my @t = @{$hash{$_}->{VAL}};
     for(my $j=$#t+1;$j<=$i-1;$j++){
      push @{$hash{$_}->{VAL}},0;
     }
     push @{$hash{$_}->{VAL}},1;
    }
    else{
     $hash{$_}->{SEQ}=$n++;
     push @{$hash{$_}->{VAL}},1;
   }
}
  close FH;
}
foreach my $key (sort {$hash{$a}->{SEQ} <=> $hash{$b}->{SEQ}} keys %hash){
  my @tmp = @{$hash{$key}->{VAL}};
  my @t = map {my $tmp=($_ == 1)?$key:" ";$tmp;} @tmp;
  print join ",", @t;
  print "\n";
}