[英]merge columns from common files from different directories and rename the column header form the directory it came from?
我对Perl代码的了解很深。 我想合并来自不同目录中名为“ file.txt”的通用文件中名为“值”的一列。 所有这些文件具有相同的行数。 这些文件有多个列,但我只想合并一个称为“值”的列。 我想创建一个合并了所有“值”列的文件,但该列的标题应从其来源目录中命名。
目录A
File.txt
ID Value location
1 50 9
2 56 5
3 26 5
目录B
File.txt
ID Value location
1 07 9
2 05 2
3 02 5
目录C
File.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脚本合并了文件中的所有列,而不是我感兴趣的特定列,并且我不知道如何重命名标头。 非常感谢您的建议。
如果您的文件用制表符分隔,则可以执行以下操作:
#!/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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.