extract multiples columns from txt file perl

后端 未结 3 1967
情歌与酒
情歌与酒 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:16

    This program does as you ask. It expects the path to the input file as a parameter on the command line, which can then be read using the empty "diamond operator" <> without explicitly opening it

    Each non-blank line of the file is split into fields, and the header line is identified by the first starting with a hash symbol #

    A call to map converts the @wanted_fields array into a list of indexes into @fields where those column headers appear and stores it in array @idx

    This array is then used to slice the wanted columns from @fields for every line of input. The fields are printed, separated by tabs

    use strict;
    use warnings 'all';
    
    use List::Util 'first';
    
    my @wanted_fields = qw/ columnA columnC columnN /;
    
    my @idx;
    
    while ( <> ) {
        next unless /\S/;
    
        my @fields = split;
    
        if ( $fields[0] =~ /^#/ ) {
    
            @idx = ( 0, map {
                my $wanted = $_;
                first { $fields[$_] eq $wanted } 0 .. $#fields;
            } @wanted_fields );
        }
    
        print join( "\t", @fields[@idx] ), "\n" if @idx;
    }
    

    output

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

提交回复
热议问题