多行字符串,保留额外的空格(缩进不变)

25 浏览
0 Comments

多行字符串,保留额外的空格(缩进不变)

我想用以下方法将一些预定义的文本写入文件:

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日
0
0 Comments

如果你想把字符串存入变量中,另一个简单的方法就是像下面这样:

USAGE=$(cat <<-END
    This is line one.
    This is line two.
    This is line three.
END
)

如果你用制表符(即'\t')缩进你的字符串,缩进就会被去掉。如果你用空格缩进,缩进就会保留下来。

注意:最后一个右括号要放在另一行。 END 文本必须单独占据一行。

0
0 Comments

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

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

0