>I have something that looks like this:
>total=0
>grep -E "pattern" file | while read line; do
> size=$(echo $line | cut -f3 -d ' ')
> total=$(($total + $size))
>done
>echo $total
>Needless to say, I get a total of 0 in the end, because the whole
>while loop executes in a subshell.
>Is there any way I can parse this file and add up the 3rd field of the
>select lines, and get a total that I can use in the rest of the script?
Sure, you could do something like this:
total=0
grep -E "pattern" file | while read line; do
size=$(echo $line | cut -f3 -d ' ')
total=$(($total + $size))
echo $total > mytotal
done
total=`cat mytotal`
rm mytotal
echo $total
but I suspect it's easier to do the whole thing like this:
total=0
total=`grep -E "pattern" file |
awk -v sum=$total '{sum+=$3} END {print sum}'`
echo $total
or the simpler (which assumes the prior total is zero):
total=`grep -E "pattern" file | awk '{sum+=$3} END {print sum}'`
echo $total
Chuck Demas
Needham, Mass.
--
Eat Healthy | _ _ | Nothing would be done at all,
Die Anyway | v | That no one could find fault with it.