bash bash中数组元素的算术
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29326212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Arithmetic with array elements in bash
提问by Vaderico
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 <
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
我想打印 ---> david 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[@]}"
回答by SMA
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
回答by user000001
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 < ""
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. You would be probably better off to do the task in awk, like this for example:
但是,在 bash 中拥有文件相当慢。您可能最好在 awk 中完成任务,例如:
awk '{s=0;for(i=1;i<=NF;i++) s+=$i;print s}' file