Created
May 13, 2020 17:17
-
-
Save mingsai/eb4429d1c1e68077958b93c5f07aeadc to your computer and use it in GitHub Desktop.
Perl - Split CSV by field value and retain header
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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