问题描述
我想用以下内容将一些预定义的文本写入文件:
I want to write some pre-defined texts to a file with the following:
text="this is line one
this is line two
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
我肯定每个后面没有空格,但是多余的空格是怎么出来的?
I'm positive that there is no space after each , but how does the extra space come out?
推荐答案
Heredoc 听起来更方便.它用于向ex 或cat
Heredoc sounds more convenient for this purpose. It is used to send multiple commands to a command interpreter program like ex or cat
cat << EndOfMessage
This is line 1.
This is line 2.
Line 3.
EndOfMessage
<<<
后面的字符串表示停止的位置.
The string after <<
indicates where to stop.
要将这些行发送到文件,请使用:
To send these lines to a file, use:
cat > $FILE <<- EOM
Line 1.
Line 2.
EOM
您也可以将这些行存储到变量中:
You could also store these lines to a variable:
read -r -d '' VAR << EOM
This is line 1.
This is line 2.
Line 3.
EOM
这会将行存储到名为 VAR
的变量中.
This stores the lines to the variable named VAR
.
打印时,请记住变量周围的引号,否则您将看不到换行符.
When printing, remember the quotes around the variable otherwise you won't see the newline characters.
echo "$VAR"
更好的是,您可以使用缩进使其在您的代码中更加突出.这次只需在 <<
后面添加一个 -
来阻止标签出现.
Even better, you can use indentation to make it stand out more in your code. This time just add a -
after <<
to stop the tabs from appearing.
read -r -d '' VAR <<- EOM
This is line 1.
This is line 2.
Line 3.
EOM
但是你必须在代码中使用制表符而不是空格来缩进.
But then you must use tabs, not spaces, for indentation in your code.
这篇关于带额外空格的多行字符串(保留缩进)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!