Created
November 16, 2014 19:55
-
-
Save tsumare/4dcd2e5557a81549c356 to your computer and use it in GitHub Desktop.
Slice files into sections by regex
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
#!/usr/bin/perl | |
use warnings; | |
use strict; | |
my $REGEX = shift @ARGV; | |
my $SourceFile = shift @ARGV; | |
my $OutputFormat = shift @ARGV; | |
my $FileI = 0; | |
open(SRC, '<', $SourceFile) or die "Unable to open $SourceFile: $!"; | |
my $OutF = undef; | |
while (<SRC>) { | |
if (my @captures = ($_ =~ /$REGEX/)) { | |
close($OutF) if (defined($OutF)); | |
printf "Opening %s\n", formatfilename($OutputFormat, $FileI, @captures); | |
open($OutF, '>', formatfilename($OutputFormat, $FileI++, @captures)); | |
} | |
unless (defined($OutF)) { | |
printf "Opening %s\n", formatfilename($OutputFormat, $FileI); | |
open($OutF, '>', formatfilename($OutputFormat, $FileI++)); | |
} | |
print $OutF $_; | |
} | |
sub formatfilename { | |
my $Format = shift; | |
my $i = 0; | |
while (@_) { | |
my $arg = shift(@_); | |
$Format =~ s/%$i/$arg/g; | |
$i++; | |
} | |
return $Format; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment