Barth
Barth

Reputation: 15745

Bash: Special characters lost when reading file

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 ?

Upvotes: 20

Views: 22050

Answers (2)

crw
crw

Reputation: 683

Can you use perl for part or all of your script requirements?

perl -lne 'print;' my.tex

If you must later shell-out to some other tool, you might still have a problem, unless you can pass the required data in a file.

Upvotes: 0

Rob I
Rob I

Reputation: 5747

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.

Upvotes: 29

Related Questions