Eric
Eric

Reputation: 13

Bash - Sum numbers in line, line by line

So I have a file which looks likes the following:

9032894 First Last 89 43 100 
9423897 First Last 89 20 48 

And so on, continuing on in this format. My hope is to get the sum of the last three numbers, (such as 89 43 100 for the first line), and then use echo to display this sum. In my attempts to do this, I just end up with the entire first column stored in one variable, as the following code does:

first=$(echo $INT | cut -d" " -f4 $1)

Would take the entire first column in the file and store it in "first". How would I go through and sum each individual line, instead of by column? (I already know how to do this using awk, I'm attempting to do an alternate way of coding using bash)? My full code thus far (which isn't even close to working) is:

#!/bin/bash

filename=$1

while read -a rows
do
    first=$(echo $INT | cut -d" " -f4 $1)
    second=$(echo $INT | cut -d" " -f5 $1)
    third=$(echo $INT | cut -d" " -f6 $1)
    echo ${first}
    echo ${second}
    echo ${third}       
done< $filename

Thanks in advance, it's much appreciated.

Upvotes: 0

Views: 1546

Answers (4)

RavinderSingh13
RavinderSingh13

Reputation: 133428

@Eric: Try:

awk '{print $NF+$(NF-1)+$(NF-2)}'  Input_file

As you have mentioned last 3 fields always we need to take the sum so we need not to go through a loop we could add their values simply by doing($NF+$(NF-1)+$(NF-2)) where $NF means last field of a line, $(NF-1) is second last field and so on.

Upvotes: 2

James Brown
James Brown

Reputation: 37394

You could also use awk:

$ awk '{s=0; for(i=4;i<=NF;i++) s+=$i; print s}' file
232
157

Upvotes: 0

choroba
choroba

Reputation: 241758

If you read a line into an array, just sum the last three elements of the array:

while read -a cells ; do
    echo $(( cells[-1] + cells[-2] + cells[-3] ))
done

Output:

232
157

Upvotes: 1

Barmar
Barmar

Reputation: 780714

You can read file columns directly into variables:

while read id firstname lastname first second third
    echo "${first}"
    echo "${second}"
    echo "${third}"   
    echo Sum: $(( first + second + third ))  
done< "$filename"

And get in the habit of quoting your variables, unless you specifically need the result to undergo word-splitting and globbing.

Upvotes: 2

Related Questions