10

Possible Duplicate:
How to iterate through the name of files in a folder

Using \input{filename}, I can input a file canned "filename.tex". I have a directory containing all of the files I want to include. How can I create a for loop, which inputs all of those files?

  • The contents of the directory sometimes changes (so I do not want to manually specify all of the files).
  • The files are numbered (e.g. file01.tex, file02.tex), so the loop should have no difficulty inputing them in the correct order.
  • Other code will be placed within the for loop (before and after the input command), so I do not want to simply list all of the files at once (e.g. \input{file01,file02}).
3

1 Answer 1

15

You can use a \foreach loop:

\documentclass{article}
\usepackage{pgffor}
\usepackage{filecontents}% Used so that the external files can be placed in this file

\begin{filecontents}{file01.tex}
  \section{File 01}
\end{filecontents}

\begin{filecontents}{file02.tex}
  \section{File 02}
\end{filecontents}

\begin{document}

\foreach \i in {00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, ...,19} {%
    \edef\FileName{file\i}%     The % here are necessary to eliminate any
    \IfFileExists{\FileName}{%  spurious spaces that may get inserted
       \input{\FileName}%       at these points
    }
}

\end{document}

Note that I added % to places where TeX would have inserted a spurious space. See for Tex Capacity Exceeded (if remove % after use of macro) as to the dangers of leaving those out.

2
  • Is there any way to define "19" (the number in the last file or value of the total number of files within the directory) automatically?
    – Village
    Dec 17, 2011 at 6:01
  • 2
    It is easier to to just use a number larger than the max number of expected files, say "99", or "999". The extra time required to check them all should be minimal. Getting the number of files in the directory is probably OS dependent. Dec 17, 2011 at 18:17

Not the answer you're looking for? Browse other questions tagged .