Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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}).
share|improve this question

marked as duplicate by Martin Scharrer Dec 17 '11 at 8:55

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

I closed this as a duplicate. The principle solutions are shown there and adding any extra code before or after is trivial. As shown there you either need to use an external script, LuaTeX or well named file names. If you think otherwise, please comment or edit your question and feel free to flag for reopening the question. –  Martin Scharrer Dec 17 '11 at 8:58
For a more advanced case see: tex.stackexchange.com/a/25261/9467 –  Please don't touch Dec 17 '11 at 11:32

1 Answer 1

up vote 6 down vote accepted

You can use a \foreach loop:

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

  \section{File 01}

  \section{File 02}


\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


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.

share|improve this answer
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 '11 at 6:01
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. –  Peter Grill Dec 17 '11 at 18:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.