Shell command to sum integers, one per line?

2019-01-01 11:53发布

I am looking for a command that will accept as input multiple lines of text, each line containing a single integer, and output the sum of these integers.

As a bit of background, I have a log file which includes timing measurements, so through grepping for the relevant lines, and a bit of sed reformatting I can list all of the timings in that file. I'd like to work out the total however, and my mind has gone blank as to any command I can pipe this intermediate output to in order to do the final sum. I've always used expr in the past, but unless it runs in RPN mode I don't think it's going to cope with this (and even then it would be tricky).

What am I missing? Given that there are probably several ways to achieve this, I will be happy to read (and upvote) any approach that works, even if someone else has already posted a different solution that does the job.

Related question: Shortest command to calculate the sum of a column of output on Unix? (credits @Andrew)


Update: Wow, as expected there are some nice answers here. Looks like I will definitely have to give awk deeper inspection as a command-line tool in general!

标签: shell
30条回答
查无此人
2楼-- · 2019-01-01 12:18

Pure bash and in a one-liner :-)

$ cat numbers.txt
1
2
3
4
5
6
7
8
9
10


$ I=0; for N in $(cat numbers.txt); do I=$(($I + $N)); done; echo $I
55
查看更多
孤独寂梦人
3楼-- · 2019-01-01 12:19

With jq:

seq 10 | jq -s 'add' # 'add' is equivalent to 'reduce .[] as $item (0; . + $item)'
查看更多
美炸的是我
4楼-- · 2019-01-01 12:21

I realize this is an old question, but I like this solution enough to share it.

% cat > numbers.txt
1 
2 
3 
4 
5
^D
% cat numbers.txt | perl -lpe '$c+=$_}{$_=$c'
15

If there is interest, I'll explain how it works.

查看更多
只靠听说
5楼-- · 2019-01-01 12:21
sed 's/^/.+/' infile | bc | tail -1
查看更多
旧时光的记忆
6楼-- · 2019-01-01 12:21

For Ruby Lovers

ruby -e "puts ARGF.map(&:to_i).inject(&:+)" numbers.txt
查看更多
流年柔荑漫光年
7楼-- · 2019-01-01 12:22

One-liner in Racket:

racket -e '(define (g) (define i (read)) (if (eof-object? i) empty (cons i (g)))) (foldr + 0 (g))' < numlist.txt
查看更多
登录 后发表回答