31

I want to write a backslash character to a text file using LaTeX.

The first line of code below declares a variable 'file' which describes the file 'myfile.out'. The second line opens the file and the third one tries do write a backslash '\' to the file.

\documentclass{article}
\begin{document}
   \newwrite\file%
   \immediate\openout\file=myfile.out%
   \immediate\write\file{\}%
\end{document}

The third line does not work because LaTeX get confused with the backslash, anyone knows how can I make it work? I tried a lot of things including \textbackslash, $\backslash$ \char ``\` etc and nothing seems to work.

Thanks a lot

Giovanni Funchal
  • 8,934
  • 13
  • 61
  • 110
  • 1
    I had the same problem. There are working answers on http://tex.stackexchange.com/questions/7359/how-to-make-a-real-backslash-escape-character – JanKanis Sep 09 '11 at 13:01

3 Answers3

20

Sound like you want a backslash in text mode; since \backslash does not work, try \textbackslash.

EDIT: \symbol{92} should also work.

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
Martijn
  • 5,471
  • 4
  • 37
  • 50
  • \textbackslash gives weird error: TeX capacity exceeded, sorry – Giovanni Funchal Jan 18 '10 at 15:48
  • Using \symbol{92}, I get a myfile.out which contains '\char 92\relax ' seems like it misses an expansion or something. – Giovanni Funchal Jan 18 '10 at 15:49
  • Maybe there are some issues with writing to text files that I'm unfamiliar with -- didn't expect this to give an error. – Martijn Jan 19 '10 at 07:43
  • I'm surprised this doesn't work, as well. Explanation, anyone? – Charles Stewart Jan 19 '10 at 20:00
  • A tentative explanation is that I think that \symbol{92} is a macro that translates to \char`92, which asks to the compiler's backend to insert the character with given number in the current font. As there is no backend when writing to files, the \char`92 macro remains unexpanded in the output. – Giovanni Funchal Jan 20 '10 at 11:24
  • In my overleaf document, even though `\textbackslash` didn't work, `\symbol{92}` solved the problem! Thanks @Martijn – keremistan Jan 01 '20 at 10:21
13

You can use \@backslashchar. The following works for me:

\documentclass{article}
\begin{document}
\newwrite\file
\immediate\openout\file=myfile.out
\makeatletter
\immediate\write\file{\@backslashchar}
\makeatother
\closeout\file
\end{document}
Alok Singhal
  • 93,253
  • 21
  • 125
  • 158
  • Does not work for me. This is what is written in the text file in place of the backslash: `\spacefactor \@m {}backslashchar` – mmj May 21 '18 at 11:07
  • Seems to work for me - but I am not a LaTeX expert, so I am not sure how to help. I ran "pdflatex ". – Alok Singhal May 22 '18 at 03:07
-1

"AB/FQS/ET004/2014" write it in latex with space as "AB/ FQS/ ET004/ 2014"