Skip to content

Instantly share code, notes, and snippets.

@tsumare
Created November 16, 2014 19:55
Show Gist options
  • Save tsumare/4dcd2e5557a81549c356 to your computer and use it in GitHub Desktop.
Save tsumare/4dcd2e5557a81549c356 to your computer and use it in GitHub Desktop.
Slice files into sections by regex
#!/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