这里字符串添加换行符

时间:2016-06-09 14:24:19

标签: bash herestring

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

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

3 个答案:

答案 0 :(得分:10)

是的,你是对的:<<<添加一个尾随的新行。

你可以看到它:

$ 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。   因此,在大多数情况下,需要最终换行。特别常见   case是使用命令susbtitution获取命令的输出,   以某种方式处理它,然后将其传递给另一个命令。命令   替换条最终换行; <<<放回一个。

答案 1 :(得分:3)

fedorqui's helpful answer显示以及为什么here-strings(以及here-documents)总是添加换行符

至于:

  

是否有方便的方法将其删除?

在Bash中,在process substitution中使用printf作为\n - 更少”替代here-string

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

应用于您的示例:

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

或者,正如user202729建议的那样,只需在管道中使用printf %s ,这样做的另一个好处是不仅可以使用更熟悉的功能,还可以使命令正常工作(更严格地说)符合POSIX标准的shell(以/bin/sh为目标的脚本):

$ printf %s 'test' | md5sum
098f6bcd4621d373cade4e832627b4f6

答案 2 :(得分:1)

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

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

“here string”也是:

$ 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
相关问题