SUM semicolon-seperated values from txt-file

Hello,

(I'm a shell beginner)
how can I sum the bold values of the following txt-file (values.txt) with bash shell. The result of the sum should be written in a new txt file (sum.txt):

...

Thanks in advance

Hello Milu,

Welcome to forum, please use code tags for the commands/inputs/codes you are using in your posts as per forum rules. Following may help you in same.

awk '{A=A?A + $NF+0:$NF+0} END{printf "%.2f\n", A > "NEW_SUM.txt"}'  Input_file

It will create a file named NEW_SUM.txt with the total of the last field.

Thanks,
R. Singh

1 Like

another solution

awk -F";" '{ sum+=$(NF-1)} END {print sum}' Input_file > Sum.txt
1 Like

thank you very much. This code works great.
Now I want to filter the sum. Only Lines with the correct Date (=02;2015) should be used for sum.

Try

awk -F";" '$4=="02"{ sum+=$(NF-1)} END {print sum}' Input_file > Sum.txt

Please decide what your requirement is before posting, anyways,, for your latest req

awk -F";" '$4$5=="022015"{ sum+=$(NF-1)} END {print sum}'
1 Like

Hello milu,

Following may help you in same too.

awk -F";" '{if($4==2){A=A?A + $(NF-1)+0:$(NF-1)+0}} END{printf "%.2f\n", A > "NEW_SUM.txt"}'  Input_file

EDIT: Or following may also work as above.

awk -F";" '{A=$4==2?A + $(NF-1)+0:$(NF-1)+0} END{printf "%.2f\n", A > "NEW_SUM.txt"}' Input_file

Thanks,
R. Singh