extract multiples columns from txt file perl

后端 未结 3 1968
情歌与酒
情歌与酒 2021-01-17 05:29

I have a txt file like this:

#Genera columnA columnB columnC columnD columnN
x1       1       3       7      0.9      2
x2       5       3       13     7            


        
3条回答
  •  有刺的猬
    2021-01-17 06:13

    You can simplify like this and using hash slices.

    #!/usr/bin/env perl
    use strict;
    use warnings;
    
    my @wanted = ( '#Genera' , qw (  columnA columnC columnN ));
    
    open my $input, '<', "file.txt" or die $!;
    
    chomp ( my @header = split ' ', <$input> ); 
    
    print join "\t", @wanted, "\n";
    while ( <$input> ) { 
       my %row;
       @row{@header} = split; 
       print join "\t", @row{@wanted}, "\n";
    }
    

    Which outputs:

    #Genera columnA columnC columnN 
    x1  1   7   2   
    x2  5   13  5   
    x3  0.1 7   0.4 
    

    If you want to exactly match your indentation then add sprintf to the mix:

    E.g.:

    print join "\t", map { sprintf "%8s", $_} @wanted, "\n";
    while ( <$input> ) { 
       my %row;
       @row{@header} = split; 
       print join "\t", map { sprintf "%8s", $_} @row{@wanted}, "\n";
    }
    

    Which then gives:

     #Genera     columnA     columnC     columnN           
          x1           1           7           2           
          x2           5          13           5           
          x3         0.1           7         0.4    
    

提交回复
热议问题