Search code examples
bashintegersumcut

Bash: Sum of integer values from stdout


Is there a way to do this?

I have a set of data which includes an integer field:

cat myinput
14 bytes long.
36 bytes long.
32 bytes long.

I would like to add the integer values in these text lines to give a sum total. So in the case of the above example, the sum total of the integer values is 82. I had thought of using something like:

cat myinput | cut -f1 -d' ' | <...add code here to add the filtered integers...> 

It seems I have to expr in some way, but I can't figure out how.

Can anyone help?


Solution

  • Let's do it with awk?

    $ awk 'a+=$1; END{print a}' file
    14 bytes long.
    36 bytes long.
    32 bytes long.
    82
    

    With bash:

    f=0
    while read i
    do
      n=$(echo $i | cut -d' ' -f1)
      tot=$(($n + $tot))
    done < file
    
    $ echo $tot
    82