# Use detokenize with command line input that has underscores

I'm calling a script where I give a command line input to LaTeX:

pdflatex "\def\myvar{given_test} \input{figures.tex}"


And then in the script, I try to use this "given_test" input and print it:

\textbf{filename: \myvar}


This breaks LaTeX, then I try to use detokenize

\textbf{filename: \detokenize{\myvar}}


And that just prints the text "\myvar"

The underscore is a necessity, since we are reading from a more complex pipeline that uses them for the file identifiers.

So how do I read what is inside \myvar and not break LaTeX.

• Try \textbf{filename: \expandafter\detokenize\expandafter{\myvar}}
– Werner
Nov 15 '13 at 3:25
• It works, but it gives a dot instead of the underscore, is understandable, but if it gave the underscores it would be great, care to write it as an answer and then you can get the sweet points? Nov 15 '13 at 3:28
• @Leonpalafox Changing \textbf onto \texttt gives underscore in the desired place. Nov 15 '13 at 4:29
• You can use \edef\myvar{\detokenize{given_test}} in the command line. Nov 15 '13 at 17:58

Together with guidelines in Handling of special LaTeX characters in text, you can expand \myvar before \detokenize-ing it:

\documentclass{article}
\usepackage[T1]{fontenc}% http://ctan.org/pkg/fontenc
\def\myvar{given_test}
\begin{document}
\textbf{filename: \detokenize\expandafter{\myvar}}
\end{document}

• Sorry for nitpicking but I think that the first \expandafter is not mandatory (as with \unexpanded). Sorry if I'm mistaken. Nov 15 '13 at 8:33
• @cjorssen You're right: \detokenize looks for the opening brace expanding tokens as it goes, so the first \expandafter is not necessary. Nov 15 '13 at 10:22

It shouldn't be difficult to change your pipeline to do

pdflatex "\edef\myvar{\detokenize{given_test}}\input{figures.tex}"


Example with figures.tex like this:

\documentclass{article}

\begin{document}

Here's the file name: \texttt{\myvar}

\input{\myvar}

\end{document}


and with given_test.tex containing

Hello World!


Compiling with the above command line gives

so you see that the variable points to the correct file name.

Note that if you need \myvar in other fonts than typewriter type, loading

\usepackage[T1]{fontenc}


in the document becomes necessary.