1

I have the following file:

lab1:/etc/scripts# cat /tmp/tmp.PGikhA/audit.txt                                
   344 server1                                                                            
     1 server2

I want to be able to add the numbers from each row together - so in this case, I want to add 344 + 1 and end up with 345.

So far, I have the following steps figured out:

lab-1:/etc/scripts# cat /tmp/tmp.PGikhA/audit.txt |awk '{print $1}'              
344                                                                                                    
1                     

But I don't know how to add them together. I know that I can just use $a + $b syntax, but how do I get the 344 and 1 into separate variables to do that?

Thanks.

EDIT 1

I'm getting two values returned instead of just the one total. Can't see what I'm doing wrong:

lab-1:/etc/scripts# cat /tmp/tmp.jcbiih/audit.txt | awk '{print $1}' | awk '{ sum+=$1} {print      
sum}'                                                                                                                    
344                                                                                                                      
345                                                                                                                      
lab-1:/etc/scripts# cat /tmp/tmp.jcbiih/audit.txt  | awk '{ sum+=$1} {print sum}'                  
344                                                                                                                      
345                                                                                                                      
  • Is the 355 a typo? – Timothy Martin Mar 14 '18 at 19:27
  • yes. just typo. will fix – dot Mar 14 '18 at 19:29
5

You can do your math in awk easily. Here is an example:

awk '{ total+=$1 } END { print total }'

If you really wanted to use bash, you could use a simple loop to read one line at a time and add it up:

count=0 
while read -r number _; do # put the first column in "number" and discard the rest of the line
    count=$(( count + number )) 
done < /tmp/foo
echo $count
  • when i try it via command line, I'm getting both 344 and 345. Please see edit 1 – dot Mar 14 '18 at 19:19
  • 2
    @dot You left off the "END", which tells awk to not print until it has finished processing all the data. – jordanm Mar 14 '18 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.