#!/usr/bin/perl use strict; use warnings; my $file = shift or die; # read csv file... my $hash; open my $fh, "<", $file; my $result = <$fh>; # grab header... while ( my $line = <$fh> ) { # then read rest of file. push @{$hash->{ [ split /,/, $line ]->[1] }}, $line; } $result .= join '', @{$hash->{$_}} for sort keys $hash; print $result; __output__ CAT_HEADER,SUPPLIER_CODE,CUSTOMER_CODE CAT_LINE,0001P,ABC12345,20190924,,1,Z,3.36 CAT_LINE,0001P,ABC23456,20190924,,1,Z,2.24 CAT_LINE,0001P,ABC34567,20190924,,1,Z,2.24 CAT_LINE,0002P,ABC12345,20190924,,1,Z,3.36 CAT_LINE,0002P,ABC23456,20190924,,1,Z,2.24 CAT_LINE,0002P,ABC34567,20190924,,1,Z,2.24