Include many files of very similar names all with one command?

I have dozens of pdf with the same name except for a changing number at the very end, e.g. xyz1.pdf, xyz2.pdf, ... xyz38.pdf.
I know the command \includepdf{}, but writing it 38 times to include all files into my new file is quite cumbersome.

Is there some command that includes all pdf from 1 to 38?

3 Answers

EDITED: I tried it to verify it works.

\documentclass{article}
\usepackage{ifthen,pdfpages}
\newcounter{countindex}
\newcommand\includemultipdf[2]{%
\setcounter{countindex}{0}%
\whiledo{\value{countindex}<#2}{%
\stepcounter{countindex}%
\includepdf{#1\arabic{countindex}.pdf}%
}
}
\begin{document}
\includemultipdf{xyz}{38}
\end{document}

• The ifthen package is to load the \whiledo{}, right? Nov 4, 2016 at 17:08
• @Lucas Yes. I have edited to make it a macro. Nov 4, 2016 at 17:09

You can use the \foreach command of tikz package:

\documentclass{scrartcl}
\usepackage{tikz}
\usepackage{pdfpages}

\begin{document}
\foreach \x in {1,2,...,38}{%
\includepdf{xyz\x.pdf}%
}
\end{document}


This way, you can also use arguments that are not numbers (e.g. \foreach \x in {a,...,f}), or couples of arguments (\foreach \x/\y in {a/1,b/2,c/3,d/4,e/5,f/6}) — see in §83. Repeating Things: The Foreach Statement in the PGF Manual how "smart" the implicit ,..., statement is.

• of course, you can define \newcommand\includemultipdf[2]{\foreach \x in {1,2,...,#2}{\includepdf{#1\x.pdf}} and use \includemultipdf{xyz}{38} as in Steven's answer. The only limitation is that you should have at least two PDF (which is a reasonable assumption if you're using this macro). Nov 4, 2016 at 17:33

There are several loop macros available.

\documentclass{article}
\usepackage{xparse}
\usepackage{pdfpages}

\ExplSyntaxOn
\NewDocumentCommand{\multiincludepdf}{O{}mm}
{
\int_step_inline:nnnn { 1 } { 1 } { #3 }
{
\includepdf[#1]{#2##1}
}
}
\ExplSyntaxOn

\begin{document}

\multiincludepdf[<options for all files>]{xyz}{38}

\end{document}


The options can be omitted.

This will load xyz1.pdf, xyz2.pdf and so on until xyz38.pdf.