How to sum the value with negative values?

Hi Gurus,

I have requirement need to sum the value, the logic is if the value is negative then time -1, I tried below two ways. one is failed, another one doesn't work.

awk -F"," '{if($8< 0 $8*-1 else $8) sum+=$8}{print sum, $8} END{printf("%.2f\n",sum)}'
 awk -F"," '{sum+=abs($8)}{print sum, $8} END{printf("%.2f\n",sum)}' 

any suggestion about this.

thanks in advance.

How about

{sum+=$8<0?-$8:$8}

?

You need to declare/define the abs function if you want to use it.

1 Like
awk -F "," '$8 < 0{$8=$8*-1} {sum+=$8} END {printf "%.2f\n", sum}' file
1 Like

Hello ken6503,

Could you please try following and let me know if this helps you.

awk  -F"," 'function abs(value){sum+=value;return sum} {abs($8)}{;print sum OFS $8} END{printf("%.2f\n",sum)}'   Input_file

EDIT: Adding one more little modified version of above solution.

awk  -F"," 'function abs(value){sum+=value;print sum OFS value} {abs($8)} END{printf("%.2f\n",sum)}'  Input_file

Thanks,
R. Singh

1 Like

As always, thanks all of you give me such great idea.

thanks again.