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.
# Read all the remaining lines in to an array and close the file.
open($fh, "<", $filename) or die "Cannot open \"$filename\" for input: $!\n";
my $column_line = "";
$column_line = <$fh> while !($column_line =~ /ABC RBC Name/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 a new header and the column line to it, then print the now sorted data to it and 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;
####
SEALEVEL SYSTEMS
SEALEVEL SYSTEMS, INC.
SEBASTIAN COMMUNICATIONS
MASQUE SOUND
MASSTECH, INC
MASTERBILT
SE INTERNATIONAL
####
MASSTECH, INC
SEALEVEL SYSTEMS, INC.
MASQUE SOUND
MASTERBILT
SE INTERNATIONAL
SEALEVEL SYSTEMS
SEBASTIAN COMMUNICATIONS
####
MASQUE SOUND
MASSTECH, INC
MASTERBILT
SE INTERNATIONAL
SEALEVEL SYSTEMS
SEALEVEL SYSTEMS, INC.
SEBASTIAN COMMUNICATIONS