1

I am trying to sum a sequence of numbers. The code that I have at the moment is

seq 0 2 100

I want to sum every even number. I am aware of the + operator used for addition. I am a newbie. I do hope that someone can point me in the right direction.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • seq 0 2 100 is the code I am trying to use. Is a loop needed? Or something simpler? I Have not learned about loops in Bash. Just a little on loops in Python – Stewart Bovis Apr 23 '20 at 21:06
  • 1
    `printf '%s\n' {0..100..2} | awk '{sum+=$1} END{print sum}'` or else `seq 0 2 100 | awk '{sum+=$1} END{print sum}'` – anubhava Apr 23 '20 at 21:08
  • `let a=$a+1`, among other possibilities (`a=(($a+1))` should be working as well). – Matthieu Apr 23 '20 at 21:10
  • 1
    Did you try other command I gave: `seq 0 2 100 | awk '{sum+=$1} END{print sum}'` – anubhava Apr 23 '20 at 21:22
  • I am getting bash: printf: '\': invalid format character for your first example anubhave. But the second exaple worked fine. That's great! Much appreciated. – Stewart Bovis Apr 23 '20 at 21:24

1 Answers1

1

Sum every even number in a sequence?

seq 100 | awk '$1 % 2 == 0 { sum += $1 } END { print sum }'

Of course, your seq already only prints out even numbers, so

seq 0 2 100 | awk '{ sum += $1 } END { print sum }'

or if you have datamash,

seq 0 2 100 | datamash sum 1
Shawn
  • 47,241
  • 3
  • 26
  • 60
  • I am getting datamash: command not found. Why is that? I am using Ubuntu 14.04 LTS if that is of relevance. – Stewart Bovis Apr 23 '20 at 21:27
  • 2
    @StewartBovis Because you don't have it installed? `apt install datamash`, if an Ubuntu version that old has it available at all. – Shawn Apr 23 '20 at 21:28
  • Why use `awk` (spawning a new process) instead of bash builtins? (That's a genuine question, more than a criticism). – Matthieu Apr 24 '20 at 06:59
  • @Matthieu If you go that way you don't even need `seq`. Probably worth an answer of its own. – Shawn Apr 24 '20 at 07:27
  • Pure shell *might* be an issue though with a lot of numbers. It isn't known for speed. – Shawn Apr 24 '20 at 07:29