将“while read line”压缩到一个数组并求和

时间:2021-08-22 18:48:25

I hope someone can help...

我希望有人能帮忙……

I've parsed integers to a file separated by carriage returns like so:

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

...
427562786
6834257
978539857
9742
578375
...

…427562786 6834257 978539857 9742 578375…

I wish to put these into an array and sum the total. However, after some fervent Googling, I can only find a reasonable way to do this using a for loop, which I'm on pretty good authority is not the best way to read a file line by line.

我想把它们放到一个数组中,并把总数加起来。然而,在经过一些*的搜索之后,我只能找到一种合理的方法来使用for循环,我很有权威地认为这不是逐行读取文件的最佳方法。

I understand that somewhere in this script I would need to declare something like this:

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

我知道在这个脚本的某个地方,我需要声明如下内容:IFS=',而读取行do数组创建魔法在这里完成< /tmp/file

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

SUM=0而read line do SUM= SUM array elements magic此处完成< /tmp/file

printf $SUM

printf和美元

Please can someone more knowledgeable than me let me know what I'm missing? Thanks. :)

请比我更有见识的人告诉我我遗漏了什么?谢谢。:)

2 个解决方案

#1


2  

If the array is only an intermediate step and not required beyond that point then this takes you straight to the final answer:

如果数组只是一个中间步骤,而不需要超过那个点,那么这将直接指向最终答案:

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

#2


1  

In bash 4, there is the mapfile command.

在bash 4中,有mapfile命令。

mapfile -t numbers < /tmp/list_of_numbers

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

In earlier versions of bash, you can use read, but it's a little more verbose:

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

IFS=$'\n' read -d '' -a numbers < /tmp/list_of_numbers

#1


2  

If the array is only an intermediate step and not required beyond that point then this takes you straight to the final answer:

如果数组只是一个中间步骤,而不需要超过那个点,那么这将直接指向最终答案:

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

#2


1  

In bash 4, there is the mapfile command.

在bash 4中,有mapfile命令。

mapfile -t numbers < /tmp/list_of_numbers

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

In earlier versions of bash, you can use read, but it's a little more verbose:

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

IFS=$'\n' read -d '' -a numbers < /tmp/list_of_numbers