The TOTAL
variable is a shell variable and therefore awk
won't know about it. In your awk
command the TOTAL
variable is unset in each iteration so it's being reset with a single value each time and then printed.
Additionally, it seems pointless to use awk
in a loop like this.
awk
can perform this operation by itself with the following 1 liner:
awk '$1 > 100 { total+=$1 } END { print total }' ipuniq.txt
No loops or other commands needed.
However, if your assignment requires you use bash/shell you could do:
total=0
while read -r p _; do
((p>100)) && total=$((total+p))
done < ipuniq.txt
echo "$total"
This will use a shell arithmetic expression to check if the value of p
is greater than 100, if so it will add it to total
.
Additionally note: I have added the -r
option to your read
command as this will print backslashes literally (likely unnecessary for your use case but I prefer to use -r
at all times unless I specifically have a reason not to.)
I have also added the _
parameter name, this will prevent p
from being set to an undesirable input. read
will assign all leftover words to the last parameter, so in your case say your file contains numbers and IPs like:
1 10.10.10.10
2 10.10.10.11
Without a parameter to catch the cruft, p
would be set to:
p='1 10.10.10.10'
then:
p='2 10.10.10.11'
awk '$1 > 100 { sum+=$1 } END { print sum }'
Awk is perfectly suited for these tasks – Valentin Bajrami Nov 17 '19 at 22:33