多行字符串,保留额外的空格(缩进不变)
多行字符串,保留额外的空格(缩进不变)
我想用以下方法将一些预定义的文本写入文件:
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
后面都没有空格,但是这个额外的空格是怎么产生的呢?
admin 更改状态以发布 2023年5月20日
Heredoc 在这个用途上更为方便。它被用来发送多个命令到命令解释器程序,如 ex 或 cat。
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
但是你必须在你的代码中使用制表符而不是空格进行缩进。