Print section numbers in header
[project-aon.git] / common / scripts / split-sections.pl
1 #!/usr/bin/env perl
2 #
3 # Split single text file with numbered sections into multiple files,
4 # one per section.
5 #
6 # Simple Bash script to add title to the resulting files:
7 #
8 # for i in `seq 1 350`; do
9 #     sed -i '1s/^/The Storms of Chai\n/' $i.txt;
10 # done
11
12 # See https://www.projectaon.org/en/Sanctum/Howto-proofread
13
14 use strict;
15 use autodie;
16 use warnings qw< FATAL all >;
17 use IO::Handle;
18 use Scalar::Util qw< openhandle >;
19
20 #Initialise variables
21 my $debug = 1;
22 my $fh = new IO::Handle;
23 my $line = "";
24 my $section = "";
25 my $filename = "";
26
27 while ($line = <>) {
28     chomp ($line);
29     print STDERR "DEBUG: Reading '$line'\n" if $debug;
30     if ($line =~ /^(\d+)$/) {
31         $section = $1 ;
32         $filename = "$section.txt";
33         print STDERR "DEBUG: Starting section $section\n" if $debug;
34         close $fh if $fh->opened();
35         open ($fh, ">>$filename") or die "Couldn't open file $filename, $!";
36         print $fh "Section $section\n";
37     } 
38
39     # Print to the file if we have a filehandle except for the 
40     # section number itself
41     if ($line !~  /^(\d+)$/) {
42         if ( $fh->opened() ) {
43             print STDERR "DEBUG: Printing to $filename\n" if $debug;
44             print $fh $line."\n" ;
45         }
46     }
47 }
48
49
50 close $fh if fileno($fh);
51
52 exit 0;