2016-08-04 80 views
7

我有一个很长的字符串可以通过echo命令打印。通过这样做,我希望它完美缩进。 我想这和它是完全工作正常如何在回声时避免空格被分割成多行

echo "This is a very long string. An"\ 
"d it is printed in one line" 

Output: 
This is a very long string. And it is printed in one line 

但是,当我尝试正确缩进它作为echo语句也缩进。它增加了额外的空间。

echo "This is a very long string. An"\ 
    "d it is printed in one line" 

Output: 
This is a very long string. An d it is printed in one line 

我找不到任何可以完美实现这一点的工作响应。

回答

5

这里的问题是,你是给两个参数echo,它的默认行为是将它们打印背部采用了空间之间:

$ echo "a"    "b" 
a b 
$ echo "a" "b" 
a b 
$ echo "a"\ 
>   "b" 
a b 

如果你想在有完全控制权你要打印,使用阵列,printf

lines=("This is a very long string. An" 
     "d it is printed in one line") 
printf "%s" "${lines[@]}" 
printf "\n" 

这将返回:

This is a very long string. And it is printed in one line 

或者为suggested by 123 in comments,使用echo还与阵列IFS设置为null:

# we define the same array $lines as above 

$ IFS="" 
$ echo "${lines[*]}" 
This is a very long string. And it is printed in one line 
$ unset IFS 
$ echo "${lines[*]}" 
This is a very long string. An d it is printed in one line 
#       ^
#        note the space 

Bash manual → 3.4.2. Special Parameters

*

($ )扩展到位置参数,从一开始。当扩展不在双引号内时,每个位置参数扩展为单独的单词。在执行的上下文中,这些单词受到进一步的单词分割和路径名扩展。当扩展出现在双引号内时,它将扩展为一个单词,每个参数的值由IFS特殊变量的第一个字符分隔。也就是说,“$”相当于“$ 1c $ 2c ...”,其中c是IFS变量值的第一个字符。 如果IFS未设置,则参数由空格分隔。如果IFS为空,则参数在没有介入分隔符的情况下连接。

有趣的阅读:Why is printf better than echo?

+0

谢谢。我正在那样做。只是为了记录,是否有可能使用'echo'? – molecule

+1

@molecule你可以在'$ {lines [@]}“中为'line'做一些事情。做; echo -n“$ line”; done'。但它有点难看,不是吗? – fedorqui

+0

是的,的确很丑。谢谢队友 – molecule