HARISH
HARISH

Reputation: 179

Arithmetic in Shell script

After executing this

ta=`zcat abc.log.2019071814.gz |grep "R_MT"|grep "A:1234"|grep "ID:413"|awk -F"|" '{print $20}'|sort|uniq -c|awk '{$1=$1};1'`

Here $20 indicates the "S:" entry in each row (I am taking the unique count of all s values),I am getting result as

93070 S:1 11666 S:8 230 S:9

so what I need is the sum of all occurrence of s values .i.e 93070+11666+230 so result be total=104966

Upvotes: 0

Views: 109

Answers (3)

Cyrus
Cyrus

Reputation: 88626

Append to your last awk:

| awk '{sum+=$1} END {print sum}'

or use this (awk ignores columns with S:1, S:8 and S:9):

echo $ta | awk '{for(i=1;i<=NF;i++) t+=$i; print t; t=0}'

or use every second column:

echo $ta | awk '{for(i=1;i<=NF;i=i+2) t+=$i; print t; t=0}'

Upvotes: 1

Chris Maes
Chris Maes

Reputation: 37742

I won't help you all the way, but know that you can use bc to perform arithmetic.

echo "93070 + 11666 + 230" | bc

would give you:

104966

Upvotes: 0

Arkadiusz Drabczyk
Arkadiusz Drabczyk

Reputation: 12393

$ echo 93070 S:1 11666 S:8 230 S:9 | sed -E 's,S:[0-9]+,,g' | sed 's,  ,+,g'  | bc -
104966

Upvotes: 2

Related Questions