> file 我想在文件中看起来像这样 -6ren">
gpt4 book ai didi

macos - 防止 "echo"解释反斜杠转义

转载 作者:行者123 更新时间:2023-12-03 13:48:31 24 4
gpt4 key购买 nike

我想将某些内容回显到包含新行转义序列的文件中,但是我希望它们保持转义状态。我正在寻找与 this 基本相反的东西题。

echo "part1\npart2" >> file

我想在文件中看起来像这样
$ cat file
old
part1\npart2

但它看起来像
$ cat file
old
part1
part2

最佳答案

这是 POSIX 推荐使用 printf 的一个很好的例子。而不是 echo (请参阅 here ,在“应用程序使用”下):您不知道 echo 会带来什么| 1.

你可以获得:

  • 内置 shell echo默认情况下不解释反斜杠转义
  • 示例:Bash 内置 echo有一个 -e选项以启用反斜杠转义解释并检查 xpg_echo shell 选项
  • 内置 shell echo默认情况下解释反斜杠转义
  • 示例:zsh、破折号
  • 一个独立的可执行文件 /bin/echo : 可能取决于哪一个 – GNU Coreutils echo懂的-e选项,比如内置的 Bash

  • POSIX 规范说明了这一点(强调我的):

    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 :
    printf '%s\n' 'part1\npart2' >> file

    哪里 \n将始终解释格式字符串中的 \n在参数中永远不会被解释,导致
    part1\npart2

    被附加到 file .

    1 有关 echo 的各种行为的详尽概述和 printf ,见 echo(1) and printf(1)在 in-ulm.de 上。

    关于macos - 防止 "echo"解释反斜杠转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43528202/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com