Adding columns of two files

Hello everyone,

I have two files containing 6 columns and thousands of rows. I want to add them (i.e. first column of first file + first column of second file and so on) and print the output in a third file. Can you please help me.

Thanks a lot

assuming your fields are 'space/tab' separated AND you want to produce one cell adding all rows in all the files for a gven column.

nawk '
   {
      for(i=1; i<= NF; i++)
         arr += $i
      nf=NF
   }
   END {
      for(i=1; i<=nf; i++)
         printf("%s%s", arr, (i<nf) ? OFS : "\n") 
   }
' file1 file2

Thanks a lot for the help. But I am not sure I made myself clear. Suppose I have files A and B (shown below) with 2 rows and 3 columns -

I just want another file with the same dimensions, just adding the corresponding element in each file.

A
1 1 1
2 2 2

B
1 1 1
3 3 3

Output file C
2 2 2
5 5 5

Does this program do that?

Thanks a lot

I am sorry. I was not clear in my first post.

nawk ' 
FNR==NR {
  for(i=1; i<=NF; i++)
    f1[FNR,i]=$i
  next
}
{
  for(i=1; i<=NF; i++)
    printf("%d%s", $i+f1[FNR,i], (i==NF) ? "\n" : FS);
}' fileA fileB

cool work!!and usefull

Thanks a lot. It was really useful.

Hi,

Thanks alot for this thread.
But, I have multiple files and want to this addition.
And then store it into a seperate file?
Is it possible to change the file names in a loop
and do this nawk operation in every iteration?

Thanks a lot...