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. Nov 14, 2014 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, 2014 at 13:52
  • "sentence" inside the argument of \input ? Nov 14, 2014 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, 2014 at 14:13
  • That period is fine I was questioning this one: {\input{\x.} Nov 14, 2014 at 14:26

1 Answer 1


You just need not escape _:



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


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:


  \clist_map_inline:nn { #2 } { #1 \input{##1} #3 }


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


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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .