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}).

1 Answer 1


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.

  • 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 .