ディレクトリ内のすべてのファイルの内容を列単位で合計する方法

ディレクトリ内のすべてのファイルの内容を列単位で合計する方法

このファイルを列単位で追加したいと思います。つまり、ファイル 1 の列 1 をファイル 2 の列 1 に追加し、同様にファイル 1 の列 2 をファイル 2 の列 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)

または、ファイルが次のような場合

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

これを行う1つの方法は次のとおりです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";
}

すべての入力ファイルの各行と列を合計します。

そのフィールドの数値以外の値はゼロとして扱われます。

行数が同じか、異なるファイルに対して機能します。

ファイル内の1行あたりのフィールド数が異なる場合でも機能することができます(たとえ出力が期待したものと異なる場合や使用できない可能性があるため推奨されません)。

おすすめ記事