【问题标题】:Bash 'while read line' into an array and sum totalBash 'while read line' 成一个数组并求和
【发布时间】:2012-08-17 17:20:04
【问题描述】:

希望有人能帮忙...

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

...
427562786
6834257
978539857
9742
578375
...

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

我知道在这个脚本的某个地方我需要声明如下内容:

IFS='
'
而读行
在这里做
数组创建魔法
完成/file

总和=0
而读行

SUM= 在这里求和数组元素
完成/file

printf $SUM

请比我知识渊博的人告诉我我缺少什么?谢谢。 :)

【问题讨论】:

    标签: linux arrays bash math while-loop


    【解决方案1】:

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

    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】:

    在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-16
      • 2014-03-31
      • 2022-11-01
      • 2015-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多