带多余空格的多行string(保留缩进)

我想写一些预定义的文本到以下文件:

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 

'<<'之后的string表示停止的地方。

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

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

您也可以将这些行存储到一个variables中:

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

这将行存储到名为VAR的variables。

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

 echo "$VAR" 

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

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

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

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 

如果你想把string变成一个variables,另一个简单的方法是这样的:

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

如果你用制表符(即'\ t')缩进你的string,缩进将被删除。 如果你用空格缩进,缩进将被留下。

注:重要的是最后一个右括号在另一行上。 END文本必须单独出现在一行上。

在一个bash脚本中,以下工作:

 #!/bin/sh text="this is line one\nthis is line two\nthis is line three" echo $text > filename 

或者:

 text="this is line one this is line two this is line three" echo "$text" > filename 

猫的文件名给出:

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

我已经find了另一种方法,因为我想每行都正确缩进:

 echo "this is line one" \ "\n""this is line two" \ "\n""this is line three" \ > filename 

如果您在行的末尾放置"\n" ,则不起作用。


或者,你可以使用printf来实现更好的可移植性(我遇到了很多echo问题):

 printf "%s\n" \ "this is line one" \ "this is line two" \ "this is line three" \ > filename 

另一个解决scheme可能是:

 text='' text="${text}this is line one\n" text="${text}this is line two\n" text="${text}this is line three\n" printf "%b" "$text" > filename 

要么

 text='' text+="this is line one\n" text+="this is line two\n" text+="this is line three\n" printf "%b" "$text" > filename