簡體   English   中英

合並來自不同目錄的通用文件中的列,並重命名來自其目錄的列標題?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM