如何在Bash命令替换结束时抑制或删除换行符?

时间:2015-11-03 16:33:46

标签: string bash output

如何在Bash command substitution结尾处抑制或删除换行符?

例如,我有

echo "$(python --version) and more text"

我如何获得

Python 2.7.10 and more text

而不是

Python 2.7.10
 and more text

2 个答案:

答案 0 :(得分:3)

这里的事情是python --version输出到stderr,而"and more text"输出到stdout。

所以你唯一需要做的就是使用2 >&1将stderr重定向到stdin:

printf "%s and more text" "$(python --version 2>&1)"

$ echo "$(python --version 2>&1) and more text"
Python 2.7.10 and more text

请注意,我最初选择了tr -d '\n' using |&

echo "$(python --version |& tr -d '\n') and more text"

答案 1 :(得分:3)

bash command substitution syntax already removes trailing newlines。您需要做的就是重定向到stdout:

$ echo "$(python --version) and more text"
Python 2.7.8
 and more text
$ echo "$(python --version 2>&1) and more text"
Python 2.7.8 and more text