I've recently discovered TexSoup, a Python module to parse Latex files inspired by BeatifulSoup. It makes really easy to work with .tex files in a very straightforward way. For instance it allows to target specific Latex commands such as \input{} in just few lines of codes.
Suppose you have a main.tex file in your folder which reads as follows:
\documentclass[12pt]{article} \begin{document} % ..other commands here.. \section{First part} \input{file1} \section{Second part} \input{file2} % ..other commands here.. \end{document}
If the files file1.tex and file2.tex are in the same folder just save the script at the bottom in a file named flatten.py and execute the command:
python flatten.py main.tex expanded.tex
to get the expanded file.
#!/usr/bin/env python3 import sys from TexSoup import TexSoup def soupify(file): """ Load file in TexSoup object. """ with open(file, 'r') as file_to_read: content = file_to_read.read() soup = TexSoup(content) return soup def flatten(soup): """ Expand \input{} commands in a tex file. """ while soup.input: soup.input.replace(flatten(soupify(soup.input.args[0]+'.tex'))) return soup if __name__ == "__main__": file = sys.argv[1] expanded_tex = flatten(soupify(file)) if len(sys.argv) > 2: output_file = sys.argv[2] else: output_file = 'output.tex' with open(output_file, 'w') as output: output.write(repr(expanded_tex)) pass
Notice: this work for Python 3 only and you have to install TexSoup before (pip install TexSoup). If you have both Python 2 and 3 installed on the same machine you may need to launch the command using python3 instead of python as first word.