【问题标题】:merge columns from common files from different directories and rename the column header form the directory it came from?合并来自不同目录的公共文件的列并将列标题重命名为它来自的目录?
【发布时间】:2013-09-29 17:33:52
【问题描述】:

我的 Perl 代码卡住了。我想从不同目录中的一个名为“file.txt”的通用文件中合并一个名为“值”的列。所有这些文件都具有相同的行数。这些文件有多个列,但我只对合并一个名为“值”的列感兴趣。我想创建一个合并了所有“值”列的文件,但列的标题应该从它来自的目录命名。

目录-A
文件.txt

ID  Value location
 1   50     9
 2   56     5
 3   26     5

目录-B
文件.txt

ID  Value location
 1   07      9
 2   05      2
 3   02      5

目录-C
文件.txt

ID  Value location
 1   21     9
 2   68     3
 3   42     5

我的输出应该是如下的组合表:

ID  Directory-A  Directory-B  Directory-C
 1   50              07           21
 2   56              06           68
 3   26              02           42

我的 perl 脚本合并了文件中的所有列,而不是我感兴趣的特定列,我不知道如何重命名标题。 非常感谢您的建议。

【问题讨论】:

  • 如果您需要脚本方面的帮助,请分享。

标签: perl


【解决方案1】:

如果您的文件是制表符分隔的,您可以执行以下操作:

#!/usr/bin/perl

use strict;
use warnings;
use autodie;

my @result;
my @files = ( "directory-a/file.txt", "directory-b/file.txt", "directory-c/file.txt" );

my $i = 0;
foreach my $filename ( @files ) {
    $result[ $i ] = [];
    open( my $file, "<", $filename );
    while ( my $line = <$file> ) {
        my @columns = split( /\t/, $line );
        push( @{ $result[ $i ] }, $columns[1] ); # getting values only from the column we need
    }
    close $file;
    $i++;
}

my $max_count = 0;
foreach my $column ( @result ) {
    $max_count = scalar( @$column ) if ( scalar( @$column ) > $max_count );
}

open ( my $file, ">", "result.txt" );
for ( 0 .. $max_count - 1 ) {
    my @row;
    foreach my $col ( @result ) {
        my $value = shift( @$col ) || "";
        push( @row, $value );       
    }
    print $file join( "\t", @row ), "\n";
};
close $file;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多