2014-06-07 85 views
-3

這是我的文件中的參考第一列將多列轉換爲行?

NoARTInfo_6 hm_database_atg_all bil|qw_N_g8589t1 
NoARTInfo_6 alia_query_atg_all alia|FBgn0028542 
NoARTInfo_7 hm_database_atg_all bil|qw_N_g7396t1 
NoARTInfo_7 alia_query_atg_all alia|rmt0034647 
WTCArcNu8_1 req_query_atg_all req|nbrL2EG020589 
WTCArcNu21_1 hm_database_atg_all bil|qw_N_g5599t1 
WTCArcNu21_1 req_query_atg_all req|nbrL2EG004245 

我想將文件轉換成它看起來文件B像

NoARTInfo_6 hm_database_atg_all bil|qw_N_g8589t1 alia_query_atg_all alia|FBgn0028542 
NoARTInfo_7 hm_database_atg_all bil|qw_N_g7396t1 alia_query_atg_all alia|rmt0034647 
WTCArcNu8_1 req_query_atg_all req|nbrL2EG020589 
WTCArcNu21_1 hm_database_atg_all bil|qw_N_g5599t1 req_query_atg_all req|nbrL2EG004245 

第一列有一定的重複標識符(這裏NoARTInfo_6NoARTInfo_7NoARTInfo_6)和一些轉換唯一標識符(這裏是NoARTInfo_6)。

第二列和第三列有它們的值。

如果第一列id被重複,那麼它們應該只在文件B中具有所有值的一次。

+3

你的問題是什麼? –

+4

請顯示您的代碼並描述您遇到的問題 – Borodin

回答

2

這AWK應該工作:

awk '!a[$1]{b[++n]=$1; a[$1]=$0; next} {k=$1; $1=""; a[k] = a[k] $0} 
    END{for (i=1; i<=n; i++) print a[b[i]]}' file 
NoARTInfo_6 hm_database_atg_all bil|qw_N_g8589t1 alia_query_atg_all alia|FBgn0028542 
NoARTInfo_7 hm_database_atg_all bil|qw_N_g7396t1 alia_query_atg_all alia|rmt0034647 
WTCArcNu8_1 req_query_atg_all req|nbrL2EG020589 
WTCArcNu21_1 hm_database_atg_all bil|qw_N_g5599t1 req_query_atg_all req|nbrL2EG004245 
1
#!/usr/bin/perl 
use strict; 
use warnings; 
my %hash; 
open (my $fh, "<", "fileA") or die $!; #Open fileA in read mode 
open (my $fh2, ">", "fileB") or die $!; #Open fileB in write mode 
while(chomp(my $line=<$fh>)){ 
    my ($key, @values) = split//, $line; 
    if(exists $hash{$key}){ 
     my $ref_value = $hash{"$key"}; 
     push @values, @$ref_value; 
     $hash{"$key"} = [@values]; 
    } 
    else{ 
     $hash{"$key"} = [@values]; 
    } 
} 
foreach(keys %hash){ 
    print $fh2 "$_ @{$hash{$_}}\n"; #Write to fileB 
} 
close($fh); 
close($fh2); 

短:

#!/usr/bin/perl 
# your code goes here 
use strict; 
use warnings; 
my %hash; 
open (my $fh, "<", "fileA") or die $!; #Open fileA in read mode 
open (my $fh2, ">", "fileB") or die $!; #Open fileB in write mode 
while(chomp(my $line = <$fh>)){ 
    my ($k, @vals) = split//, $line; 
    push @{ $hash{$k} }, @vals; 
} 
foreach(keys %hash){ 
    print $fh2 "$_ @{$hash{$_}}\n"; #Write to fileB 
} 
1
#!/usr/bin/perl 

while (<>) { 
    my ($key, @list) = split; 
    push(@keys, $key) if !defined $hash{$key}; 
    push(@{$hash{$key}}, @list); 
} 
foreach (@keys) { 
    print join(' ', ($_, @{$hash{$_}})), "\n"; 
} 

輸出

./script.pl data 
NoARTInfo_6 hm_database_atg_all bil|qw_N_g8589t1 alia_query_atg_all alia|FBgn0028542 
NoARTInfo_7 hm_database_atg_all bil|qw_N_g7396t1 alia_query_atg_all alia|rmt0034647 
WTCArcNu8_1 req_query_atg_all req|nbrL2EG020589 
WTCArcNu21_1 hm_database_atg_all bil|qw_N_g5599t1 req_query_atg_all req|nbrL2EG004245 

我不確定這些行的順序是否重要,但我保留它在任何情況下。