我想写一些预定义的文本与以下文件:
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之后没有空间,但额外的空间是如何出来的?
Echo在传递给它的参数之间添加空格。$text受变量扩展和单词分割的影响,所以你的echo命令相当于:
echo -e "this" "is" "line" "one\n" "this" "is" "line" "two\n" ...
你可以看到在“this”之前加了一个空格。你可以删除换行符,并引用$text来保留换行符:
text="this is line one
this is line two
this is line three"
echo "$text" > filename
或者你可以使用printf,它比echo更健壮和可移植:
printf "%s\n" "this is line one" "this is line two" "this is line three" > filename
在支持大括号展开的bash中,你甚至可以这样做:
printf "%s\n" "this is line "{one,two,three} > filename