linux – 当分割成多行时,如何避免echo中的空格

前端之家收集整理的这篇文章主要介绍了linux – 当分割成多行时,如何避免echo中的空格前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个很长的字符串由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

我找不到任何可以完美做到这一点的工作反应.

解决方法

这里的问题是你给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开始:

*

($) Expands to the positional parameters,starting from one. When the expansion is not within double quotes,each positional parameter expands to a separate word. In contexts where it is performed,those words are subject to further word splitting and pathname expansion. When the expansion occurs within double quotes,it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is,“$” is equivalent to “$1c$2c…”,where c is the first character of the value of the IFS variable. If IFS is unset,the parameters are separated by spaces. If IFS is null,the parameters are joined without intervening separators.

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

猜你在找的Linux相关文章