Search code examples
linuxshellcsh

Calculating a sum of numbers in C shell


I'm trying to calculate a sum numbers positioned on separate lines using C shell.

I must do it with specific commands using pipes.

There is a number of commands: comand.. | comand.. | (comands...) printing lines in the following form:

1
2
8
4
7

The result should be 22, since 1 + 2 + 8 + 4 + 7 = 22.

I tried ... | bc | tr "\n" "+" | bc, but it didn't work.

I can't use AWK, or variables. That is why I am asking for help.


Solution

  • You actually can use the C shell variables, as they are part of the syntax. Without using variables, you need to pipe, and pipe again:

    your-command | sed '2~1 s/^/+/' | xargs | bc
    

    The sed command prepends plus character to all lines starting from the second; xargs joins the lines as a sequence of arguments.

    The SED expression can be improved to filter out non-numeric lines:

    '/^[^0-9]\+$/ d; 2~1 s/\([0-9]\+\)/+\1/'