【问题标题】:How to replace a file's content with a string containing new line characters?如何用包含换行符的字符串替换文件的内容?
【发布时间】:2014-05-11 23:36:35
【问题描述】:

当我将“line1\nline2\nline3”读入字符串时,如下所示:

read string

line1\nline2\nline3

然后回显字符串并将输出定向到文件:

echo $string > text.txt

txt 文件现在包含:

line1nline2nline3

我怎样才能使文件包含:

line1
line2
line2

?

谢谢。

【问题讨论】:

    标签: linux bash shell scripting


    【解决方案1】:

    这里的问题是\n 并不意味着换行。它只是不必要地转义了n 的值。

    做你想做的,你应该做的。

    1. 以保留反斜杠的方式读取字符串
    2. 展开所有转义序列并写出字符串

    您可以 1. 使用 read -r 和 2. 使用 echo -e:

    read -r string
    echo -e "$string"
    

    【讨论】:

    • +1 为正确答案。对于OP,请阅读BashFAQ/001了解更多详情。
    【解决方案2】:

    只需将$string 放在双引号中即可:

    echo "$string" > text.txt
    

    【讨论】:

      【解决方案3】:

      您需要添加双引号。

      例子:

      $ example=line1\nline2
      $ echo $example
      line1nline2
      

      双引号:

      $ example="line1\nline2"
      $ echo $example
      line1
      line2
      

      保存:

      $ echo $example >> example.txt
      $ cat example.txt
      line1
      line2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-06
        • 1970-01-01
        • 1970-01-01
        • 2018-10-13
        • 2016-10-30
        • 2014-06-12
        相关资源
        最近更新 更多