Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Special characters lost when reading file

Tags:

I have a file containing some Latex :

\begin{figure}[ht]
 \centering
 \includegraphics[scale=0.15]{logo.pdf}
 \caption{Example of a pdf file inclusion}
 \label{fig:pdfexample}
\end{figure}

I want to read it in a bash script :

while read line
  do
    echo $line
  done < "my.tex"

The output is

begin{figure}[ht]
centering
includegraphics[scale=0.15]{logo.pdf}
caption{Example of a pdf file inclusion}
label{fig:pdfexample}

Why did I lose the backslashes and initial spaces ?

How to preserve them ?

like image 716
Barth Avatar asked Jul 19 '12 16:07

Barth


1 Answers

You lost the backslashes and spaces because bash (via its read builtin) is evaluating the value of the text - substituting variables, looking for escape characters (tab, newline), etc. See the manpage for some details. Also, echo will combine whitespace.

As far as preserving them, I'm not sure you can. You'd probably get the backslashes back by doing:

while read -r line
  do
    echo $line
  done < "my.tex"

which should modify read to not try to evaluate the backslashes. It will probably still swallow the leading spaces, though.

Edit: setting the $IFS special variable to the empty string, like this:

export IFS=

will cause the spaces to be preserved in this case.

like image 61
Rob I Avatar answered Sep 21 '22 15:09

Rob I