arrays - bash 中数组元素的算术运算

标签 arrays bash math arithmetic-expressions

我正在使用 bash 并尝试添加从文件创建的数组的所有元素。

while read line; do
    array=($line);
    sum=0
    length=${#array[@]}
    for i in ${array[@]:0:$length}; do
       sum=$[$sum+${array[i]}]   #<--- this doesn't work?
    done
    echo $sum
done < $1

编辑: 我应该更清楚为什么我想在 for 循环中使用数组拆分

输入可能是 ------> david 34 28 9 12

我想打印 ---> david 83

所以我想遍历所有元素接受第一个。所以我会使用:

length=$[${#array[@]} - 1]
for i in${array[@]:1:$length}

因此我不能使用:

for i in "${array[@]}"

最佳答案

尝试使用 expr 添加两个表达式,例如:

sum=$(expr "$sum" + "${arr[i]}")

或者

sum=$((sum + arr[i]))


echo "11 13" >test.txt 
echo "12" >>test.txt

while read -a line; do ##read it as array
    sum=0
    for ((i=1; i < ${#line}; i++)); do ##for every number in line
       sum=$(expr "$sum" + "${line[i]}") ## add it to sum
    done
    echo $line[0] $sum ##print sum
done < test.txt
Output
36

OP 编辑​​后:

echo “ABC 11 13”>test.txt echo "DEF 12">>test.txt

while read -a line; do ##read it as array
sum=0
for ((i=1; i < $((${#line[@]})); i++)); do ##for every number in line
   sum=$(expr "$sum" + "${line[i]}") ## add it to sum
   if [[ $i -eq $((${#line[@]}-1)) ]]
   then
       echo "${line[0]} $sum" ##print sum
       sum=0
   fi
done
done < test.txt
Output:
ABC 24
DEF 12

关于arrays - bash 中数组元素的算术运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29326212/

相关文章:

javascript - 运行函数几次后未定义索引

javascript - Lodash/Javascript 比较数组或对象,如果任何 Prop 匹配则失败

bash - 如果代理关闭,请获取一个新代理

ios - 使用 iosMath 使用 swift 3 显示数学公式

python - 如何在 Python 中使用蒙特卡罗方法计算 10 维球体的体积?

PHP逆时针旋转矩阵

json - bash JSON with jq - 如何检查空的 JSON 成员?

bash - ./deploy.sh 不适用于 gitlab ci

javascript - 大数 - JavaScript 中的数学

javascript - 查找第一个非重复字符javascript