The UNIX and Linux Forums  
Hello and Welcome from United States to the UNIX and Linux Forums! Thank You for Visiting and Joining Our Global Community.

Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #6 (permalink)  
Old 04-25-2008
era era is offline Forum Advisor  
Herder of Useless Cats (On Sabbatical)
  
 

Join Date: Mar 2008
Location: /there/is/only/bin/sh
Posts: 3,652
For adding the values, is it enough if you get the sum at the end? Then awk is all you need:

Code:
awk '/Segment/ { gsub("secs",""); time += $3 } END { print time }' file.txt
If you really genuinely want to loop over the cumulative times and do something which each in the shell, that would be something like

Code:
awk '/Segment/ { gsub ("secs",""); time += $3; print $3, time } file.txt |
while read THISTIME SUMTIME; do
  echo This time, we got $THISTIME
  echo Sum so far is $SUMTIME
done
The shell's arithmetic facilities are integer only, so you can't sum numbers with fractional parts in the shell itself. Getting awk to print both the current and the cumulative value for each line is a nice workaround for that (and a good opportunity to demonstrate how to read multiple values from the same line in the shell).