Skip to content

Instantly share code, notes, and snippets.

@mingsai
Created May 13, 2020 17:17
Show Gist options
  • Save mingsai/eb4429d1c1e68077958b93c5f07aeadc to your computer and use it in GitHub Desktop.
Save mingsai/eb4429d1c1e68077958b93c5f07aeadc to your computer and use it in GitHub Desktop.
Perl - Split CSV by field value and retain header
open $fh, '<', $ARGV[0];
while ($line = <$fh>) {
print $line;
if ($. == 1) {
$header = $line;
} else {
# $fields[2] is the 3rd column
@fields = split /,/, $line;
# save line into hash %c
$c{"$fields[2].csv"} .= $line;
}
}
close $fh;
for $file (keys %c) {
print "$file\n";
open $fh, '>', $file;
print $fh $header;
print $fh $c{$file};
close $fh;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment