可能重复:
如何迭代文件夹中文件的名称
使用\input{filename}
,我可以输入一个名为“filename.tex”的文件。我有一个目录,其中包含我想要包含的所有文件。如何创建一个 for 循环来输入所有这些文件?
- 目录的内容有时会发生变化(所以我不想手动指定所有文件)。
- 文件已编号(例如
file01.tex
)file02.tex
,因此循环应该可以毫无困难地按照正确的顺序输入它们。 - 其他代码将放置在 for 循环内(命令之前和之后
input
),所以我不想简单地一次列出所有文件(例如\input{file01,file02}
)。
答案1
您可以使用\foreach
循环:
\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}
请注意我添加了%
在 TeX 可能插入虚假空格的地方添加了空格。请参阅Tex 容量超出范围(如果在使用宏后删除%)以及忽略这些因素的危险。