#!/usr/bin/perl -w use warnings; use strict; my @desired_cols = qw(colname1 colname3); my @desired_cols1= qw(colname3); my $temp = 'tmp.txt'; # reads first line to get actual column names open(S1, 'S1.txt') || die "Can't open S1: $!"; open(S2, 'S2.txt') || die "Can't open S2 : $!"; open(OUT, ">$temp") || die "Can't create output : $!"; my $header_line = (); my $header_line1 = (); 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; my @slice1 = map{$col2_num{$_}}@desired_cols1; print OUT join("\t","@desired_cols"),"\r\n"; #header line # print colname1 colname3 colname3 in outfile while (, ) { my @row = (split)[@slice]; my @row1 = (split)[@slice1]; print OUT join("\t","@row @row1"),"\r\n"; #each data row }