Adding grep'd results in a variable

Here is one I am baffled with; I have not used unix for a while and now that I am back it has been fun remembering and I have enjoyed it, for the most past. this is in ksh.

I need to search in a file for the line with X1 and cut columns 20-25, put them into a variable, added them (dollar amounts with no decimal), then display the answer in a new variable. Here is what ALMOST works.

num=`grep "^X1" filename|cut -c20-25`

What this does is display the variable ($num) as 000351 000656 001254 009558

The number of entries in the variable $num in dynamic. So, I guess what I need help with is adding the numbers in the variable $num. Any assistance will be thankful....

Hi

sum=`echo $num | awk '$1=$1' OFS="+" | bc`

Guru.

1 Like
echo $num | awk '{for(i=0;++i<=NF;)c+=$i}END{printf "%06d\n",c}'

No need for bc, awk can do the job.

That did it! Works like a charm.