0

I want to add these files column wise i.e. column 1 of file 1 should be added to column 1 of file 2 and so on...., similarly column 2 of file 1 should be added to column 2 of file 2 ......

Col1(File1) + Col1(File2) + Col1(File3) .............. + Col1(File'n') = Col1(output_file)

Col2(File1) + Col2(File2) + Col2(File3) .............. + Col2(File'n') = Col2(output_file)

or if the files are like this

File 1          File 2          File n                   Output File 
a   d           b   e           c   f               a+b+...+c   d+e+....+f
c   d           c   d           a   b               c+c+...+a   d+d+....+b
e   f           e   f           a   b                   .       .
g   h      +    g   h           a   b               .       .
.   .           .   ......+......   .       =       .       .
.   .           .   .           .   .                   .       .
.   .           .   .           .   .                   .       .
.   .           .   .           .   .                   .       .
.   .           .   .           .   .                   .       .
  • 1
    can you paste here the real format of your file? are the columns separated by spaces? Do you want to append each file to the end of the previous file? – Bruno Negrão Zica Jul 5 '16 at 4:13
  • Also, show what code you have tried so far. – John1024 Jul 5 '16 at 4:45
  • Also, do all the files have the same number of columns and rows? If not what do you want when one or the other runs out? Errors or infill are both options. Is the number of files known beforehand? It does sound like this might be well suited to awk. But, making it robust depends on so much info you haven't included. – MAP Jul 5 '16 at 5:02
1

Here's one way of doing it in perl:

#!/usr/bin/perl

use strict;

my @lines=();

# read and sum the columns of all input files.
foreach my $file (@ARGV) {
  my $lc=0;   # line counter

  open(FH,'<',$file) or die "couldn't open $_ for write: $!\n";

  while (<FH>) {
    # split columns by whitespace.  change to suit your input.
    my @fields=split;

    my $fc=0;   # field counter

    while ($fc < @fields) {
      $lines[$lc]->[$fc] += $fields[$fc++];
    };
    $lc++;
  };

  close(FH);
};

# now output the summed lines
foreach my $lc (0..@lines-1) {
  # output columns separated by a TAB (\t).  Change as required.
  print join("\t", @{ $lines[$lc] } ),"\n";
}

Sums columns for each line for all input files.

Non-numeric values in fields are treated as 0.

Works with files that have the same or different numbers of lines.

It even works if files have varying numbers of fields per line (although the output may not be what you expect or even usable - not recommended).

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.