#!/usr/bin/perl use utf8; use 5.022; use strict; # Open the file for input, discard all the header lines, but stop on and save the column names in an array. # Then read all the remaining lines in to an array and close the file. my $filename = "test.txt"; my $fh; open($fh, "<", $filename) or die "Cannot open \"$filename\" for input: $!\n"; my $column_line = ""; $column_line = <$fh> while !($column_line =~ /Invoice ID/i); chomp(my @columns = split /\t/, $column_line); chomp(my @data_lines = <$fh>); close $fh; # Sort the data lines according to the "Company Name" field, and then the "Invoice ID" field. my ($company_name_index) = grep { $columns[$_] eq "Company Name" } (0..$#columns); my ($invoice_ID_index) = grep { $columns[$_] eq "Invoice ID" } (0..$#columns); @data_lines = sort { my($company_name_a, $invoice_ID_a) = (split /\t/, $a)[$company_name_index, $invoice_ID_index]; my($company_name_b, $invoice_ID_b) = (split /\t/, $b)[$company_name_index, $invoice_ID_index]; fc($company_name_a) cmp fc($company_name_b) or $invoice_ID_a <=> $invoice_ID_b } @data_lines; # Open the file for output, print the standard header to it, print the now sorted data to it, then close the file. open($fh, ">", $filename) or die "Cannot open \"$filename\" for output: $!\n"; print $fh "Replacement Header Text Here\n\n$column_line"; print $fh "$_\n" foreach @data_lines;