gpt4 book ai didi

string - 带有额外空格的多行字符串(保留缩进)

转载 作者:行者123 更新时间:2023-11-29 08:37:03 27 4
gpt4 key购买 nike

我想将一些预定义的文本写入包含以下内容的文件:

text="this is line one\n
this is line two\n
this is line three"

echo -e $text > filename

我期待这样的事情:

this is line one
this is line two
this is line three

但是得到了这个:

this is line one
this is line two
this is line three

肯定每个\n后面没有空格,但是多余的空格是怎么出来的呢?

最佳答案

Heredoc 听起来更方便。它用于将多个命令发送到命令解释程序,如 excat

cat << EndOfMessage
This is line 1.
This is line 2.
Line 3.
EndOfMessage

<<之后的字符串指示停止的位置。

要将这些行发送到文件,请使用:

cat > $FILE <<- EOM
Line 1.
Line 2.
EOM

您还可以将这些行存储到一个变量中:

read -r -d '' VAR << EOM
This is line 1.
This is line 2.
Line 3.
EOM

这会将行存储到名为 VAR 的变量中.

打印时,请记住变量周围的引号,否则您将看不到换行符。

echo "$VAR"

更好的是,您可以使用缩进使其在代码中更加突出。这次只要加一个-<< 之后停止显示标签。

read -r -d '' VAR <<- EOM
This is line 1.
This is line 2.
Line 3.
EOM

但是您必须在代码中使用制表符而不是空格来缩进。

关于string - 带有额外空格的多行字符串(保留缩进),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23929235/

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