Unix Shell脚本一起添加数组元素

Bob*_*T28 7 unix arrays bash shell

我不太了解数组,但我试图添加由"read -a"命令的用户输入定义的数组元素.

per*_*eal 12

read -a array
tot=0
for i in ${array[@]}; do
  let tot+=$i
done
echo "Total: $tot"
Run Code Online (Sandbox Code Playgroud)


gni*_*urf 12

给定一个数组(整数),这里有一个有趣的方法来添加它的元素(在bash中):

sum=$(IFS=+; echo "$((${array[*]}))")
echo "Sum=$sum"
Run Code Online (Sandbox Code Playgroud)

例如,

$ array=( 1337 -13 -666 -208 -408 )
$ sum=$(IFS=+; echo "$((${array[*]}))")
$ echo "$sum"
42
Run Code Online (Sandbox Code Playgroud)

亲:没有循环,没有子壳!

Con:仅适用于整数

编辑(2012/12/26).

随着这篇文章的提升,我想与你分享另一个有趣的方式,使用dc,然后不仅限于整数:

$ dc <<< '[+]sa[z2!>az2!>b]sb1 2 3 4 5 6 6 5 4 3 2 1lbxp'
42
Run Code Online (Sandbox Code Playgroud)

这条精彩的线条增添了所有数字.干净,嗯?

如果您的数字在数组中array:

$ array=( 1 2 3 4 5 6 6 5 4 3 2 1 )
$ dc <<< '[+]sa[z2!>az2!>b]sb'"${array[*]}lbxp"
42
Run Code Online (Sandbox Code Playgroud)

事实上,有一个负数的问题.数字'-42'应该给dcas _42,所以:

$ array=( -1.75 -2.75 -3.75 -4.75 -5.75 -6.75 -7.75 -8.75 )
$ dc <<< '[+]sa[z2!>az2!>b]sb'"${array[*]//-/_}lbxp"
-42.00
Run Code Online (Sandbox Code Playgroud)

会做.

Pro:使用浮点数.

Con:使用外部进程(但如果你想进行非整数运算,则别无选择 - 但这dc可能是此任务中最轻的).

  • 那超出了我的头脑:-| (2认同)

F-3*_*000 7

我的代码(我实际使用的)的灵感来自gniourf_gniourf的答案。我个人认为这更易于阅读/理解和修改。还接受浮点,而不仅仅是整数。

数组中的总和值:

arr=( 1 2 3 4 5 6 7 8 9 10 )
IFS='+' sum=$(echo "scale=1;${arr[*]}"|bc)
echo $sum # 55
Run Code Online (Sandbox Code Playgroud)

进行很小的更改,就可以得到平均值:

arr=( 1 2 3 4 5 6 7 8 9 10 )
IFS='+' avg=$(echo "scale=1;(${arr[*]})/${#arr[@]}"|bc)
echo $avg # 5.5
Run Code Online (Sandbox Code Playgroud)


Ban*_*ana 6

gniourf_gniourf 的答案非常好,因为它不需要循环或 bc。对于任何对实际示例感兴趣的人,这里有一个函数,它可以汇总从 /proc/cpuinfo 读取的所有 CPU 内核,而不会与 IFS 混淆:

# Insert each processor core count integer into array
cpuarray=($(grep cores /proc/cpuinfo | awk '{print $4}'))
# Read from the array and replace the delimiter with "+"
# also insert 0 on the end of the array so the syntax is correct and not ending on a "+"
read <<< "${cpuarray[@]/%/+}0"
# Add the integers together and assign output to $corecount variable
corecount="$((REPLY))"
# Echo total core count
echo "Total cores: $corecount"
Run Code Online (Sandbox Code Playgroud)

我还发现,当从双括号内调用数组时,算术扩展可以正常工作,无需读取命令:

cpuarray=($(grep cores /proc/cpuinfo | awk '{print $4}'))
corecount="$((${cpuarray[@]/%/+}0))"
echo "Total cores: $corecount"
Run Code Online (Sandbox Code Playgroud)

通用的:

array=( 1 2 3 4 5 )
sum="$((${array[@]/%/+}0))"
echo "Total: $sum"
Run Code Online (Sandbox Code Playgroud)


Ame*_*man 5

我是简洁的粉丝,所以这是我倾向于使用的:

IFS="+";bc<<<"${array[*]}"
Run Code Online (Sandbox Code Playgroud)

它本质上只是列出数组的数据并将其传递给 BC 进行评估。“IFS”是内部的分隔字段,它本质上指定了如何分隔数组,我们说用加号分隔它们,也就是说当我们把它传入BC时,它会收到一个用加号分隔的数字列表,所以很自然它将它们加在一起。