【问题标题】:How to avoid spaces in echo when it is split into multiple linesecho 拆分为多行时如何避免空格
【发布时间】:2016-08-04 21:15:45
【问题描述】:

我有一个很长的字符串要由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

我找不到任何可以完美做到这一点的有效响应。

【问题讨论】:

    标签: linux bash shell


    【解决方案1】:

    这里的问题是你给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 为 null,则连接参数而不插入分隔符。

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

    【讨论】:

    • 谢谢。我正在这样做。仅作记录,是否可以使用echo
    • @molecule 你可以做类似for line in "${lines[@]}"; do; echo -n "$line"; done 的事情。不过有点丑不是吗?
    • 是的,确实很丑。谢谢老哥
    • @molecule for echo 您可以将 IFS 更改为空,然后使用 ${lines[*]} 打印数组
    猜你喜欢
    • 2017-02-18
    • 2016-05-08
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 2020-07-23
    • 2022-10-13
    相关资源
    最近更新 更多