ken6503
November 16, 2016, 11:16am
1
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.
RudiC
November 16, 2016, 12:04pm
2
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
ken6503
November 16, 2016, 9:50pm
5
As always, thanks all of you give me such great idea.
thanks again.