添加空格分隔数字列表

时间:2017-03-19 22:03:52

标签: shell sh

目前我要求用户输入一行中间有空格的数字,然后让程序显示延迟的数字,然后添加它们。我把所有东西都弄下来了,但似乎无法找出一行代码来连贯地计算他们输入的总和,因为我的大部分尝试都以错误结束,或者最终的数字乘以第二个(甚至不确定如何?)。任何帮助表示赞赏。

echo Enter a line of numbers to be added.
read NUMBERS

COUNTER=0 

for NUM in $NUMBERS
do

    sleep 1
    COUNTER=`expr $COUNTER + 1`
    if [ "$NUM" ]; then
        echo "$NUM"
    fi
done

我已经尝试了回复expr $NUM + $NUM但收效甚微,但实际上我只能做到这一点。

2 个答案:

答案 0 :(得分:0)

设置两个变量 n m ,将它们的总和存储在 $ x 中,打印出来:

n=5 m=7 x=$((n + m)) ; echo $x

输出:

12

以上语法与POSIX兼容(即适用于dashkshbash等);来自man dash

   Arithmetic Expansion
     Arithmetic expansion provides a mechanism for evaluating an arithmetic
     expression and substituting its value.  The format for arithmetic expan‐
     sion is as follows:

           $((expression))

     The expression is treated as if it were in double-quotes, except that a
     double-quote inside the expression is not treated specially.  The shell
     expands all tokens in the expression for parameter expansion, command
     substitution, and quote removal.

     Next, the shell treats this as an arithmetic expression and substitutes
     the value of the expression.

在OP中完成大部分工作的两个单行:

  1. POSIX:

    while read x ; do echo $(( $(echo $x | tr ' ' '+') )) ; done
    
  2. bash

    while read x ; do echo $(( ${x// /+} )) ; done
    
  3. bash calc,(允许对实数,有理数和复数进行求和,以及子操作):

    while read x ; do calc -- ${x// /+} ; done
    

    示例输入行,后跟输出:

    -8!^(1/3) 2^63 -1                   
    9223372036854775772.7095244707464171953
    

答案 1 :(得分:0)

开始
NUMBERS="4 3 2 6 5 1"
echo $NUMBERS

您的脚本可以更改为

sum=0
for NUM in ${NUMBERS}
do    
    sleep 1
    ((counter++))
    (( sum += NUM ))
   echo "Digit ${counter}: Sum=$sum"
done
echo Sum=$sum

另一种方法是使用bc,对1.6 2.3

等输入很有用
sed 's/ /+/g' <<< "${NUMBERS}" | bc