Bash:读取文件时丢失特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11564778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:48:47  来源:igfitidea点击:

Bash: Special characters lost when reading file

bashescaping

提问by Barth

I have a file containing some Latex :

我有一个包含一些 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 :

我想在 bash 脚本中阅读它:

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 ?

如何保存它们?

回答by Rob I

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 manpagefor some details. Also, echo will combine whitespace.

您丢失了反斜杠和空格,因为 bash(通过其 read 内置函数)正在评估文本的值 - 替换变量、寻找转义字符(制表符、换行符)等。有关详细信息,请参阅联机帮助页。此外,echo 将合并空格。

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.

这应该修改 read 以不尝试评估反斜杠。不过,它可能仍会吞噬领先的空间。

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

编辑:将$IFS特殊变量设置为空字符串,如下所示:

export IFS=

will cause the spaces to be preserved in this case.

在这种情况下将导致保留空间。

回答by crw

Can you use perlfor part or all of your script requirements?

您可以perl用于部分或全部脚本要求吗?

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.

如果您稍后必须使用其他工具,您可能仍然会遇到问题,除非您可以在文件中传递所需的数据。