2

Is there a way to escape underscores (or other special characters) in variable names in a \foreach loop when calling file names? E.g., \foreach \x in {file\_1, name\_2}{Here is \x.} gives correct output (ie, 'Here is file_1. Here is file_2'), but \foreach \x in {file\_1, name\_2}{\input{\x}} gives an error that file 'file_1' cannot be found.

  • 1
    use \string_ and \usepackage[T1]{fontenc} so that underscores print as underscores. Why the . in \input{\x.} ? looks wrong. If you don't need to print the name just using _ is enough. – David Carlisle Nov 14 '14 at 13:43
  • Thanks, \string_ works! The . is there because it's the end of the sentence; doesn't give me any problems. – Matthijs Nov 14 '14 at 13:52
  • "sentence" inside the argument of \input ? – David Carlisle Nov 14 '14 at 13:55
  • I think we are misinterpreting each other...I just meant that the . is there as a period to end the sentence 'Here is file_1.'. – Matthijs Nov 14 '14 at 14:13
  • That period is fine I was questioning this one: {\input{\x.} – David Carlisle Nov 14 '14 at 14:26
4

You just need not escape _:

\documentclass{article}
\usepackage{pgffor}

\begin{document}

\foreach \x in {file_1, file_2}{\input{\x}\par}

\end{document}

I have two files called file_1.tex and file_2.tex containing just

I'm file 1

(and 2 in the second file).

enter image description here

Note that \foreach does its work inside a group, so this may not be the best choice. A different approach uses expl3:

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\multiinput}{+O{}m+O{}}
 {
  \clist_map_inline:nn { #2 } { #1 \input{##1} #3 }
 }
\ExplSyntaxOff

\begin{document}

\multiinput[Here: ]{file_1,file_2}[\par]

\end{document}

The optional argument can contain code to be executed before and respectively after inputting the file (it's not necessary to have either of them).

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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