[英]Arithmetic with array elements in bash
I'm using bash and trying to add all elements of an array that was created from a file. 我正在使用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
edit: I should have been clearer why i want to use array splitting in for loop 编辑:我应该更清楚为什么我想在for循环中使用数组拆分
The input may be ------> david 34 28 9 12 输入可能是------> david 34 28 9 12
And I want to print ---> david 83 我想打印--->大卫83
So I would like to loop through all elements accept the first one. 所以我想循环遍历所有元素接受第一个。 so i would use:
所以我会用:
length=$[${#array[@]} - 1]
for i in${array[@]:1:$length}
because of this i can't use: 因为这个我不能用:
for i in "${array[@]}"
Try using expr to add two expression something like: 尝试使用expr添加两个表达式,如:
sum=$(expr "$sum" + "${arr[i]}")
Or 要么
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
After OP's edit: OP编辑后:
echo "ABC 11 13" >test.txt echo "DEF 12" >>test.txt 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
If you want to sum the numbers in each lines of the file using a loop in bash you could do 如果你想使用bash中的循环对文件的每一行中的数字求和,你可以这样做
#!/bin/bash
while read line; do
array=($line);
sum=0
length=${#array[@]}
for i in ${array[@]:0:$length}; do
sum=$[$sum+$i]
done
echo $sum
done < "$1"
The difference with your code is that i
is the element in the array, not the index. 与代码的不同之处在于
i
是数组中的元素,而不是索引。
However, possessing files in bash is rather slow. 但是,在bash中拥有文件的速度相当慢。 You would be probably better off to do the task in awk, like this for example:
你可能最好在awk中完成任务,例如:
awk '{s=0;for(i=1;i<=NF;i++) s+=$i;print s}' file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.