加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

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

发布时间:2020-12-13 19:19:32 所属栏目:Linux 来源:网络整理
导读:我有一个很长的字符串由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. 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?.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读