【问题标题】:How can I stop a here string (<<<) from adding a line break or new lines?如何阻止此处的字符串 (<<<) 添加换行符或新行?
【发布时间】:2016-10-10 06:26:13
【问题描述】:

here string 似乎正在添加换行符。有没有方便的删除方法?

$ string='test'
$ echo -n $string | md5sum
098f6bcd4621d373cade4e832627b4f6  -
$ echo $string | md5sum
d8e8fca2dc0f896fd7cb4cb0031ba249  -
$ md5sum <<<"$string"
d8e8fca2dc0f896fd7cb4cb0031ba249  -

【问题讨论】:

  • &lt;&lt;&lt; 还添加了尾随换行符

标签: bash herestring


【解决方案1】:

是的,你是对的:&lt;&lt;&lt; 添加一个尾随新行。

你可以看到它:

$ cat - <<< "hello" | od -c
0000000   h   e   l   l   o  \n
0000006

让我们将其与其他方法进行比较:

$ echo "hello" | od -c
0000000   h   e   l   l   o  \n
0000006
$ echo -n "hello" | od -c
0000000   h   e   l   l   o
0000005
$ printf "hello" | od -c
0000000   h   e   l   l   o
0000005

所以我们有桌子:

         | adds new line |
-------------------------|
printf   |      No       |
echo -n  |      No       |
echo     |      Yes      |
<<<      |      Yes      |

来自Why does a bash here-string add a trailing newline char?

大多数命令都需要文本输入。在 unix 世界中,a text file consists of a sequence of lines, each ending in a newline。 所以在大多数情况下,需要最后一个换行符。一个特别常见的 案例是使用命令替代来获取命令的输出, 以某种方式处理它,然后将其传递给另一个命令。命令 替换去掉最后的换行符; &lt;&lt;&lt; 放回一个。

【讨论】:

  • 另外,请注意,here-string 是单行 here 文档的快捷方式,它始终以换行符结尾。
【解决方案2】:

fedorqui's helpful answer 显示 这里的字符串(以及这里的文档)总是附加一个换行符

至于:

有没有方便的删除方法?

在 Bash 中,在 process substitution 中使用 printf 作为 "\n-less" 替代 here-string

... < <(printf %s ...)

应用于您的示例:

$ md5sum < <(printf %s 'test')
098f6bcd4621d373cade4e832627b4f6

或者,正如user202729 所建议的那样,只需在管道中使用printf %s,这样不仅可以使用更熟悉的功能,而且可以使命令在(更严格) 符合 POSIX 的 shell(在针对 /bin/sh 的脚本中):

$ printf %s 'test' | md5sum
098f6bcd4621d373cade4e832627b4f6

【讨论】:

    【解决方案3】:

    作为“here doc”添加换行符:

    $ string="hello test"
    $ cat <<_test_ | xxd
    > $string
    > _test_
    0000000: 6865 6c6c 6f20 7465 7374 0a              hello test.
    

    “这里的字符串”也可以:

    $ cat <<<"$string" | xxd
    0000000: 6865 6c6c 6f20 7465 7374 0a              hello test.
    

    在换行符上获取非结尾字符串的最简单解决方案可能是printf

    $ printf '%s' "$string" | xxd
    0000000: 6865 6c6c 6f20 7465 7374                 hello test
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-01
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      • 1970-01-01
      相关资源
      最近更新 更多