我有bash函数get_total
,它会像这样创建输出:
0.5 0.5 0.2 1.7
只有一个空格可以分开
如果我运行命令
get_total|paste -sd+
我将输出
0.5+0.5+0.2+1.7
可以传递给不列颠哥伦比亚省
但是此命令
result=$(get_total|paste -sd+|bc)
给我这样的输出
0.5+0.5+0.2++1.7
您可能会看到两个++在bash中调用语法错误
茂请有人帮我吗?哪里出现++?如何避免这种情况?
答案 0 :(得分:0)
首先,我建议为此使用awk。以下任何一项都可以:
$ get_total | awk 'BEGIN{RS=" "}{s+=$1}END{print s}'
$ get_total | awk '{for(i=1;i<=NF;++i)s+=$i; print s}'
如果您想使用bc,则可以执行以下操作:
$ get_total | tr ' ' '+' | bc
很遗憾,我无法复制双'+',因此我无法对此发表评论。
答案 1 :(得分:0)
我不确定这是最好的方法,但是代码对我有用。
while IFS= read -r line
do
# The -z test means true if empty. ! negates (i.e. true if not empty).
if [ ! -z "$line" ]; then
result=$(get_total | paste -sd+ | tr -s '++' '+' | bc)
echo $result
fi
done < <(printf '%s\n' "$app00" "$app01")