Summing over specific lines and replacing the lines with the sum using sed, awk

Hi friends,

This is sed & awk type question.

I have a text file which has numbers spread all over the file. I want to sum the series of numbers whenever i find it and produce an output file with the sum. For example

###start of input text file ####

abc
def
ghi
1
2
3
4
kjld
random
text
occupies
some
1000
3000
400
again
some
random
text
900
100
whatever
is here
900
11
what

#####end of input file #########

The output should be

##start of output file ####

abc
def
ghi
10
kjld
random
text
occupies
some
4400
again
some
random
text
1000
whatever
is here
911
what

########### end of output file #################

So the output file is the same as the input file, except the series of numbers is replace by its sum.

I hope it makes sense. If not, please let me know any questions.

Kind Regards,

Try:

awk '!/^[0-9]+$/&&p{print s;s=0;p=0};!/^[0-9]+$/;/^[0-9]+$/,/^[0-9]+$/{s+=$0;p=1}' file
1 Like
awk '/[^0-9]/{if(s)print s; s=0; print; next} {s+=$1} END{if(s)print s}' infile
1 Like

bartus11 and Scrutinizer

Dude!

I am so grateful to both of you.

Warm Regards,
kaaliakahn