防止“回声"从解释反斜杠转义 [英] Prevent "echo" from interpreting backslash escapes
问题描述
我想向包含新行转义序列的文件回显某些内容,但是我希望它们保持转义状态.我正在寻找与这个问题基本相反的东西. >
I'd like to echo something to a file that contains new line escape sequences, however I would like them to remain escaped. I'm looking for basically the opposite to this question.
echo "part1\npart2" >> file
我想在文件中看起来像这样
I would like to look like this in the file
$ cat file
old
part1\npart2
但是看起来像
$ cat file
old
part1
part2
推荐答案
这是POSIX建议使用printf
而不是echo
的一个很好的例子(请参阅echo 1 .
This is a good example of why POSIX recommends using printf
instead of echo
(see here, under "application usage"): you don't know what you get with echo
1.
您可以获得:
- 默认情况下不解释反斜杠转义的内置Shell
echo
- 示例:内置的Bash
echo
具有-e
选项以启用反斜杠转义解释并检查xpg_echo
shell选项
- A shell builtin
echo
that does not interpret backslash escapes by default- Example: the Bash builtin
echo
has an-e
option to enable backslash escape interpretation and checks thexpg_echo
shell option
- 示例:zsh,破折号
POSIX规范说明了这一点(重点是我):
The POSIX spec says this (emphasis mine):
应支持以下操作数:
string
要写入标准输出的字符串.如果第一个操作数是-n
,或者任何操作数包含<backslash>
字符,则结果是实现定义的.The following operands shall be supported:
string
A string to be written to standard output. If the first operand is-n
, or if any of the operands contain a<backslash>
character, the results are implementation-defined.因此,对于便携式解决方案,我们可以使用
printf
:So, for a portable solution, we can use
printf
:printf '%s\n' 'part1\npart2' >> file
其中格式字符串中的
\n
将始终被解释,而参数中的\n
将永远不会被解释,从而导致where the
\n
in the format string will always be interpreted, and the\n
in the argument will never be interpreted, resulting inpart1\npart2
被附加到
file
.1 For an exhaustive overview of various behaviours for
echo
andprintf
, see echo(1) and printf(1) on in-ulm.de.这篇关于防止“回声"从解释反斜杠转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Example: the Bash builtin
- 示例:内置的Bash