我有一个包含数千个数字的文件,每个数字都在自己的行上:

34
42
11
6
2
99
...

我想写一个脚本,它将打印文件中所有数字的总和。我有一个解决办法,但不是很有效。(运行需要几分钟。)我在寻找一个更有效的解决方案。有什么建议吗?


当前回答

另一个选择是使用jq:

$ seq 10|jq -s add
55

-s(——slurp)将输入行读入数组。

其他回答

另一个是为了好玩

sum=0;for i in $(cat file);do sum=$((sum+$i));done;echo $sum

或者再来一次

s=0;while read l; do s=$((s+$l));done<file;echo $s

但awk解决方案可能是最好的,因为它最紧凑。

这是直接的Bash:

sum=0
while read -r line
do
    (( sum += line ))
done < file
echo $sum

更简洁:

# Ruby
ruby -e 'puts open("random_numbers").map(&:to_i).reduce(:+)'

# Python
python -c 'print(sum(int(l) for l in open("random_numbers")))'

c++“俏皮话”:

#include <iostream>
#include <iterator>
#include <numeric>
using namespace std;

int main() {
    cout << accumulate(istream_iterator<int>(cin), istream_iterator<int>(), 0) << endl;
}

在去:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    sum := int64(0)
    for scanner.Scan() {
        v, err := strconv.ParseInt(scanner.Text(), 10, 64)
        if err != nil {
            fmt.Fprintf(os.Stderr, "Not an integer: '%s'\n", scanner.Text())
            os.Exit(1)
        }
        sum += v
    }
    fmt.Println(sum)
}