我有一个很长的字符串,可以通过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
我找不到任何可以完美做到这一点的工作回应。
答案 0 :(得分:6)
这里的问题是你给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:
<强> * 强>
($ )从1开始扩展到位置参数。当扩展不在双引号内时,每个位置参数都会扩展为单独的单词。在执行它的上下文中,这些单词受到进一步的单词拆分和路径名扩展的影响。当扩展发生在双引号内时,它会扩展为单个单词,每个参数的值由IFS特殊变量的第一个字符分隔。也就是说,&#34; $ &#34;相当于&#34; $ 1c $ 2c ...&#34;,其中c是IFS变量值的第一个字符。 如果未设置IFS,则参数以空格分隔。如果IFS为null,则连接参数时不会插入分隔符。