gpt4 book ai didi

linux - 当它被分成多行时如何避免 echo 中的空格

转载 作者:IT王子 更新时间:2023-10-29 00:31:56 25 4
gpt4 key购买 nike

我有一个很长的字符串要用 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 一起使用:

# 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 - 当它被分成多行时如何避免 echo 中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38765151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com