in reply to Extracting selected column names and values from tab delimited text file
Code winds up with an ordered list of column positions to print and then does that for the data in the file by using list slice.
#!/usr/bin/perl -w use strict; my @desired_cols = qw(colname1 colname3); #order matters here # reads first line to get actual column names my $header_line = (<DATA>); my @actual_cols = split(/\s+/,$header_line); # get column number of the actual column names my $pos =0; my %col2_num = map {$_ => $pos++}@actual_cols; # translate the desired col names into position numbers my @slice = map{$col2_num{$_}}@desired_cols; print join("\t",@desired_cols),"\n"; #header line while (<DATA>) { my @row = (split)[@slice]; print join("\t",@row),"\n"; #each data row } =pod Prints: colname1 colname3 val1 val3 val11 val31 val12 val32 =cut __DATA__ colname1 colname2 colname3 val1 val2 val3 val11 val21 val31 val12 val22 val32
|
|---|
| Replies are listed 'Best First'. |
|---|