Reputation: 12502
Consider this awk example that sums up all values of a particular field in a file:
awk '{sum+=$2} END{print "total: ",sum}' file.txt
When the file is empty awk won't output anything for sum. Is it possible to output '0' in those cases?
Upvotes: 0
Views: 66
Reputation: 203254
In order of my preference (most to least preferred) for this specific use-case:
awk '{sum+=$2} END{print "total: ",sum+0}' file.txt
or
awk '{sum+=$2} END{printf "total: %d\n",sum}' file.txt
or
awk 'BEGIN{sum=0} {sum+=$2} END{print "total: ",sum}' file.txt
Upvotes: 3