简体   繁体   中英

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 .ie 93070+11666+230 so result be total=104966

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

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}'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM