Operating System - Linux
1755882 Members
3924 Online
108838 Solutions
New Discussion юеВ

Re: using awk to calculate

 
SOLVED
Go to solution
lawrenzo_1
Super Advisor

using awk to calculate

Hello all,

I am attempting to use awk to calculate some numbers. I have put the figures into a file from the df command:

# cat mydf.out

2424
4246432
32434672
323
5432521
43433
etc etc

I want to add them all together with the total being displayed at the end - have attempted with no luck:

cat mydf.out |awk 'BEGIN {tot=0} {tot=+$1} END {print tot}'

how can I do this using awk please?

many thnaks
hello
7 REPLIES 7
spex
Honored Contributor
Solution

Re: using awk to calculate

Hi Lawrenzo,

# awk '{a+=$1} END {print a}' mydf.out

PCS
IT_2007
Honored Contributor

Re: using awk to calculate

I use the following script to calculate total used space from bdf output.

#!/usr/bin/sh
#
BDFMEGS=/usr/local/bin/bdfmegs
if [ ! -x $BDFMEGS ]
then
echo "ERROR: $BDFMEGS does not exist!"
exit 1
fi

SUM=0

# Cut out the first line from output
$BDFMEGS | sed '1,1d' | grep -v : | while read a b c d e f
do
SUM=`expr $SUM + $c`
#echo $SUM
done

echo "Total Space Used (MB) = $SUM"
Mike Stroyan
Honored Contributor

Re: using awk to calculate

You had {tot=+$1} where you meant to have {tot+=$1} .
Awk was very non-judgemental and just did what it was told. :-)
Sandman!
Honored Contributor

Re: using awk to calculate

Or simply use the long form instead of the compact one to avoid confusion i.e.

cat mydf.out |awk 'BEGIN {tot=0} {tot=tot+$1} END {print tot}'
Marvin Strong
Honored Contributor

Re: using awk to calculate

just switch your =+ to += and your fine, however you might be awarded the useless use of cat award. ;p

awk '{tot+=$1}END{print tot}' mydf.out
lawrenzo_1
Super Advisor

Re: using awk to calculate

Thanks very much guys, much appreciated.

10 out of 10 for me for the useles cat award!!

It's a bad habit I am trying to break.

Chris.
hello
lawrenzo_1
Super Advisor

Re: using awk to calculate

;-)
hello