3

我希望有人能帮帮忙...

我已将整数解析为由回车符分隔的文件,如下所示:

...
427562786
6834257
978539857
9742
578375
...

我希望将这些放入一个数组中并求和。然而,经过一番热切的谷歌搜索后,我只能找到一种合理的方法来使用 for 循环来做到这一点,我很有权威,这并不是逐行读取文件的最佳方法。

我知道在这个脚本的某个地方我需要声明这样的东西:

IFS='
'
while read line
do
array creation magic here
done < /tmp/file

SUM=0
while read line
do
SUM= sum array elements magic here
done < /tmp/file

printf $总和

请比我更有知识的人告诉我我错过了什么?谢谢。:)

4

2 回答 2

2

如果数组只是一个中间步骤并且不需要超出该点,那么这将带您直接获得最终答案:

sum=0
while read N
do
    # sum=$((sum+N)) - the line below shows a more concise syntax
    ((sum += N))
    echo "Added $N to reach $sum"
done < /tmp/list_of_numbers

echo $sum
于 2012-08-22T09:59:15.343 回答
1

在 bash 4 中,有mapfile命令。

mapfile -t numbers < /tmp/list_of_numbers

for n in "${numbers[@]}"; do
    (( sum += n ))
done

在早期版本的 bash 中,您可以使用read,但它有点冗长:

IFS=$'\n' read -d '' -a numbers < /tmp/list_of_numbers
于 2012-08-22T12:42:22.353 回答