sum of the amounts in a file should be stored as single value in an shell variable

H|~^20200425|~^abcd|~^sum
R|~^abc|~^2019-03-06T12:33:52.27|~^1000123.34567|~^2018-04-12T12:33:52.27|
R|~^abc|~^2019-03-05T12:33:52.27|~^111930.02876|~^2018-10-23T12:33:52.27|
R|~^abc|~^2019-03-05T12:33:52.27|~^2112320.028|~^2018-10-24T12:33:52.27|
R|~^abc|~^2019-03-06T12:33:52.27|~^12230.0809|~^2018-09-11T12:33:52.27|
R|~^abc|~^2019-03-05T12:33:52.27|~^3076543789.00878|~^2018-08-05T12:33:52.27|
R|~^abc|~^2019-03-06T12:33:52.27|~^156655.0389|~^2018-10-23T12:33:52.27|
R|~^abc|~^2019-03-06T12:33:52.27|~^10453.0489|~^2018-04-08T12:33:52.27|
R|~^abc|~^2019-03-05T12:33:52.27|~^20654.0907|~^2018-07-23T12:33:52.27|

I need to get the sum of the total amounts in the 4th field for the record starts from ‘R’. I wanted sum of amounts of all the rows to be stored in a variable. how to achieve it

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

variable=$( awk -F '^' '$1 == "R|~" { sum += $4 } END { print sum }' file )

The awk command treats the data as ^-delimited and sums the 4th field up from each line that has an R in the first field, and then prints the sum when all data has been read. The non-numerical data at the end of the field (the string |~) will be ignored during the conversion of the field’s data to a numerical value.

The output of the awk command is then assigned to a variable using a standard command substitution.


For really big numbers, use bc:

variable=$(
    awk -F '^' '$1 == "R|~" { sub("\|.*","",$4); print $4 "+\" } END { print "0" }' file  |
    bc
)

This prints out the sum as a computation for bc to handle. The bc utility is a standard arbitrary precision calculator.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x