Skip to content

Instantly share code, notes, and snippets.

@msridhar
Created March 23, 2012 21:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msridhar/2175152 to your computer and use it in GitHub Desktop.
Save msridhar/2175152 to your computer and use it in GitHub Desktop.
perl script for merging .tex files and BibTeX output into single .tex file
#!/usr/bin/perl
# mergetex.pl
#
# Script for merging tex files into a single monolithic file. This
# script should make it easy to generate an ArXiV-friendly single
# .tex file from a paper that is broken into subfiles using LaTeX's
# \input{} command.
#
# USAGE:
# ./mergetex.pl [input] [output]
# ./mergetex.pl mypaper.tex mypaperMerged.tex
#
# mergetex takes two arguments, the [input] file and the [output]
# file into which the merged files should go. It recursively
# searches [input] and adds any file given by uncommented \input{}
# commands.
#
# v0.1 by Anand Sarwate (asarwate@alum.mit.edu) with tips from Erin Rhode.
# Modified by Manu Sridharan to also merge in BibTeX output.
use IO::File;
if ( scalar(@ARGV) != 2) {
die "Syntax Error : use 'mergetex.pl [input] [output]'"
}
$infile = shift;
$outfile = shift;
print "Generating tex file from $infile and storing in $outfile.\n";
my $outputfh = new IO::File($outfile, "w") or die "Could not open $outfile: $!\n";
my $inputfh = new IO::File($infile, "r") or die "Could not open $infile: $!\n";
parsetex($inputfh,$infile);
$outputfh->close();
sub parsetex {
my $fh = shift;
my $file = shift;
print "Found $file. Merging into $outfile.\n";
while (<$fh>) {
# strip out comments
$decom = $_;
$decom =~ s/^\%.*$/\%/;
$decom =~ s/([^\\])\%.*$/\1\%/g;
# search for lines with "\input{}"
if ($decom =~ /\\input{(.*?)}/) {
#get new file name
if ($1 =~ /.tex/) {
my $newfile = $1;
} else {
$newfile = $1 . ".tex";
}
# recurse to input new file
my $newfh = new IO::File($newfile, "r") or die "Could not open $infile: $!\n";
parsetex($newfh,$newfile);
} elsif ($decom =~ /\\bibliography{(.*?)}/) {
# try to input the .bbl file; if it doesn't exist, just copy
# the file
my $bblfile = $infile;
$bblfile =~ s/\.tex/.bbl/g;
my $bblfh;
if ($bblfh = new IO::File($bblfile, "r")) {
parsetex($bblfh,$bblfile);
} else {
$outputfh->print($decom);
}
}
else {
$outputfh->print($decom);
}
}
$fh->close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment