I have a file containing 3 columns (comma as delimiter). The first column contains ID, while the second and third contain values that I would like to sum. The sum should be appended as 4th column to the file in the output.
However, there could be some cases in which the third column is empty (2nd row of the input file as example). In this case, the column related to the sum has to be empty. However, when a field is explicitly 0
, the sum should be calculated as usual (i.e. 4th row of the input file).
- input.txt
2309,-0.3,0.2 2311,1.2, 2312,0,-1 2315,2.2,0
- Desired output:
2309,-0.3,0.2,-0.1 2311,1.2,, 2312,0,-1,-1 2315,2.2,0,2.2
I saw previously similar discussion but I don't know how specify that the sum should be done between the 2nd and the 3rd column and how to skip sum for row in which third column is empty. The script below should sum all values contain in the same row (also ID??), can I modify this in some way or could you suggested me another faster way?
NF++; $NF=sum
awk -v OFS=, -F, 'NR>1{sum=0; for(i=1; i<=NF; i++) sum += $i; NF++; $NF=sum } 1'
NR>1
. Does this mean that there is a header line that should be ignored? Also, can there be empty lines?