Saving/Adding integer values after string is found in text file

Viewed 41

I would like to know how I can sum up the integers of text1+text2+text3 from a text file, but if text2 and/or text3 doesnt exist after text1 then I get the integer from text1 only and look for the next text2 and/or text3 after text1.

example textfile:
text1:102        
text2:123        
text3:1432       
text1:12             
text1:34324      
text3:234234      

Desired output:

102+123+1432
12
34324+234234

or 

1657
12
268558

I am not too sure how to get this integer value and store it.

2 Answers
$ cat a.awk
function printsum() { print t1+t2+t3; t1=t2=t3=0 }
BEGIN {FS=":"}
$1 == "text1" && NR > 1 { printsum() }
$1 == "text1" { t1 = $2 }
$1 == "text2" { t2 = $2 }
$1 == "text3" { t3 = $2 }
END  { printsum() }


$ awk -f a.awk file
1657
12
268558

I was going to wait til you posted your attempt, but since you already have an answer...

$ cat tst.awk
BEGIN { FS=":" }
$1 == key { print tot; tot=0 }
{ tot += $2 }
NR==1 { key=$1 }
END { print tot+0 }

$ awk -f tst.awk file
1657
12
268558
Related